我有以下代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream in("test.txt");
in.seekp(10);
string testStr;
in >> testStr;
cout << testStr;
return 0;
}
文件“test.txt”包含以下文本:
1
2
3
4
5
6
7
8
9
10
当我在Windows上编译此代码并运行时,我获得输出= 5,当我在Linux Mint 17上编译此代码并运行时,我得到输出= 6.
为什么?
答案 0 :(得分:4)
这只是一个猜测,但在Windows中,编辑器倾向于将换行符写为两个字符:\n\r
,而在linux中它只是\n
。因此,您可以在Windows中看到您的文件:
1\n\r
2\n\r
3\n\r
4\n\r
5\n\r
在Linux中
1\n
2\n
3\n
4\n
5\n
6\n
因此,在Windows中,将搜索者移动到10将在4之后将其置于\n
,从而将其提取为5。在Linux中,搜索者将继续使用6,从而将其提取出来。要测试我的猜测是否正确,请尝试将Windows文件复制到Linux,反之亦然。
答案 1 :(得分:1)
当指定10个字节时,将计算并包含用于Linux的换行符(\ n)和回车符(\ r)+换行符(\ f)。 在Windows上,试试这个:
in.seekp(10*3);
同样,在Linux中,
in.seekp(10*2);
但是,相反,如果您读取整行10次并丢弃更好的输入,以防每行有多个字符