我在Debian x64 PC上运行的c ++程序中有一个奇怪的行为。
我无法先读取文件,然后写入另一个值,然后再读取这些值。我已经阅读了很多信息,包括关于stackoverflow的问题,发现(也通过实验)我需要同时更改seekp和seekg,并且这样做了。一切正常...直到我从流中读取了一些内容。读取操作后,如果我要查找文件的开头,然后调用tellg(),tellp(),它们都将返回“ -1”。
测试代码:
void testFstreamSeekp() {
fstream in("file", ios::in | ios::out);
cout << "g: " << in.tellg() << endl;
cout << "p: " << in.tellp() << endl;
in.seekp(0, ios_base::end);
cout << "endp g: " << in.tellg() << endl;
cout << "endp p: " << in.tellp() << endl;
in.seekp(0, ios_base::end);
in.seekg(0, ios_base::end);
cout << "end g: " << in.tellg() << endl;
cout << "end p: " << in.tellp() << endl;
in.seekp(0, ios_base::beg);
in.seekg(0, ios_base::beg);
cout << "beg …Run Code Online (Sandbox Code Playgroud)