为什么我必须为文件末尾的 seekg 提供负两个偏移量

Why I have to give a negative two offset for seekg for end of file

所以我正在阅读有关文件处理的内容,并想从最后读取一个文本文件。所以我决定使用

来寻找指向最后一个字符的指针

seekg(-2,ios::end);

我的完整代码是:

fin.open("source.txt");
fin.seekg(-2,ios::end);

fin>>ch;
if(fin.fail())
    cout<<"uh oh!";
else
    cout<<ch;

我的问题是为什么我必须将偏移量设置为 -2 而不是 -1,因为我假设 ios::end 将 get 指针指向文件最后一个有效字符之后的一个位置。

有什么帮助吗? 谢谢

您出错的原因是您使用了 >> 并且最后一个字符肯定是 '\n' 或 space。

使用 -1 搜索将您定位在 '\n' 上,但它被提取器 >> 忽略(它 skips all whitespaces 和 '\n')。如果您在前面放置一个字符,使用 -2,您肯定会到达最后一个非 space 字符并且它有效。

要真正了解文件末尾的情况:

in.open("source.txt");
fin.seekg(-1,ios::end);  // -1 is really the last char of the file 

ch = fin.get();  // read one character without ignoring anything
if(fin.fail())
    cout<<"uh oh!";
else
    cout<<(int)ch <<"="<<ch<<endl;  // display char code (if not printable) and char