为什么我必须为文件末尾的 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'
或空格。
使用 -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
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 向指针地址添加 20 个字节偏移量
- 将多个偏移量的多个元素插入到一个矢量中
- 具有多个偏移量的写入进程内存C++
- 获取第 n 项与 std::set 中第一个/最后一个的偏移量
- 为什么我必须为文件末尾的 seekg 提供负两个偏移量
- 两个相同大小(和长度)的数组是否具有相同的元素偏移
- 这两个偏移宏有什么区别
- 相同的偏移量在OpenGL中的共享型统一缓冲对象中为4个不同的浮点数