【问题标题】:tellg() and seekg() does't work properlytellg() 和 seekg() 不能正常工作
【发布时间】:2014-05-27 08:03:11
【问题描述】:
    ifstream fin;
    fin.open("c:\\1\\a.txt");

    if(fin)
    {
            string readWord1;
            streampos currentPos;
            while(fin >> readWord1)
            {
                    currentPos = fin.tellg();
                    string readWord2;
                    while(fin >> readWord2)
                    {
                            Memo1->Text = Memo1->Text + AnsiString(readWord2.c_str());
                            Memo1->Text = Memo1->Text + "\n";
                    }
                    fin.seekg(currentPos);
                    streampos c = fin.tellg();
            }
    }

我想在读取完 readWord1 之后的所有单词后返回指向 currentPos 的文件指针。但在第一步 streampos c 表示指针在 -1 中,因此 seekg() 不会将指针移动到 currentPos

【问题讨论】:

  • 你需要在调用seekg之前做fin.reset()

标签: c++ file stream


【解决方案1】:

根据文档(或至少一个版本):

如果在调用之前设置了 eofbit 标志,则函数失败(设置 失败位并返回)。

您需要使用fin.clear() 清除eofbit,然后它会按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 2019-05-05
    • 2013-12-28
    • 2023-02-04
    • 2012-07-11
    • 2012-09-24
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多