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

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

本文关键字:偏移量 两个 seekg 文件 为什么      更新时间:2023-10-16

所以我正在阅读有关文件处理的信息,并希望从末尾读取文本文件。所以我决定使用,

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'或空格。

使用 -1 查找会将您定位在""上,但提取器>>忽略它(它会跳过所有空格和"")。 如果你在前面放置一个字符,用-2,你肯定会得到最后一个非空格字符,它有效。

要真正查看文件末尾发生了什么,请执行以下操作:

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