c++ - 在 ifstream 上的 getlines [耗尽文件] 之后 seekg 的问题

标签 c++ fstream

我正在尝试编写一个程序来打印文件的最后一行,然后我想出了以下方法。我在文件中执行 SEEKs 的地方,但这段代码在无限循环中运行。如果我注释掉 (1) 并启用 (2),代码可以正常工作。我无法找出原因。

#include <iostream>
#include <fstream>

int main()
{
    std::string line;
    int count = 0;
    long int seek_length = -1l;// should be -100l
    std::ifstream ifile("D:\\cprog\\test.csv");// --(1)
    while(true){
        seek_length *= 2;
        count = 0;
        //std::ifstream ifile("D:\\cprog\\test.csv"); //-- (2)
        ifile.seekg(seek_length, std::ios_base::end);
        while(std::getline(ifile,line)){
            ++count;
        }
        if(count > 1)
            break;
    }
    std::cout << line << '\n';
}

编译器:g++ (GCC) 4.9.2 (MINGW)

最佳答案

在再次阅读之前,您需要清除流中的错误状态:

ifile.clear();

否则,第一次遇到 EOF 时,流会进入错误状态,所有后续读取都将失败。

请注意,如果您执行此操作并且您的文件仅包含 1(或 0)行,则当前形式的代码将永远循环。

关于c++ - 在 ifstream 上的 getlines [耗尽文件] 之后 seekg 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34304723/

相关文章:

c++ - 如何在 SFML 中为 Sprite 制作动画

c++ - DiceSum - 如果骰子总和不是特定数字,如何扩展 if/if-else 语句以重新掷骰子

c++ - 不确定性 std::system_error: what(): 不允许操作

c++ - 使用 fstream 读取后写入

c++ - VS Express 2015 Win10 应用程序 - ifstream 无法打开文件

c++ - 重载运算符时可以使用标志吗?

c++ - 简单的 boost 智能指针语法问题

c++ - 使用标准 C++ fstream 在串行设备 (/dev/ttyGS0) 上读写?

c++ - 如何读取文件然后在打开文件时写入文件?

c++ - 读取多个 .txt 文件 c++ linux