开发者社区> 问答> 正文

C++读文件没读完就结束,eof已用

a123456678 2016-03-23 11:41:03 869

这段代码是我写哈夫曼编码的一个解压函数,现在的问题是,没有把我整个文件解压完,像图里面,只解压了一部分然后 ,还有剩下很多没读,
貌似是eof为真,导致读文件结束了 这是怎么回事啊?

void readCodeFile()
{
ifstream inf;
ofstream outf;
int w[200], c = 0;
char s[200]; 
string code;
HuffTreeTreeArray[100];
HuffNode tempNode;
char tempChar=0;
int k = 9;
inf.open("test.txt",ios::in);
inf >> c;

for (int i = 0; i < c; i++)
{
    s[i] = inf.get();
    inf >> w[i];
    //cout << s[i] << "\t" << w[i] << "\t"<<i<<endl;
}


Word *word = new Word[c];

for (int i = 0; i < c; i++)
{
    word[i].val = s[i];
    word[i].frq = w[i];
}

for (int i = 0; i < c + 1; i++)
{
    TreeArray[i] = new HuffTree<char>(s[i], w[i]);
}


HuffTree<char> *Tree = buildHuff(TreeArray, c);

codeBuild(Tree->root(), code, word, c);

outf.open("decode.txt");
tempNode = Tree->root();
while (!inf.eof())
{   
    if (k<8)
    {
        if (((tempChar >> (7 - k)) & 1) == 0)
        {
            tempNode = ((IntlNode<char>*) (tempNode))->right();
        }
        else if (((tempChar >> (7 - k)) & 1) == 1)
        {
            tempNode = ((IntlNode<char>*) (tempNode))->left();
        }

        if (tempNode->isLeaf())
        {
            outf << ((LeafNode<char>*) (tempNode))->val();
        //  cout << ((LeafNode<char>*) (tempNode))->val();
            tempNode = Tree->root();
        }
        k++;
    }
    else
    {
        tempChar = inf.get();
        cout << tempChar;
        k = 0;
    }       
}

inf.close();
outf.close();
}
分享到
取消 提交回答
全部回答(1)
  • a123456678
    2019-07-17 19:10:40

    你用的是文本方式读取文件吧?加密内容可能会包含字符0,而文本方式读取是吧0判断为eof的。
    要用二进制方式读取。

    0 0