我在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 g: " << in.tellg() << endl;
cout << "beg p: " << in.tellp() << endl;
// Everything is fine until here (that is tellp() == 0, tellg() == 0)
int a, b;
in >> a >> b;
cout << "a: " << a << endl << "b: " << b << endl;
// tellg() == -1, tellp() == -1 ?????????!!!!!!!!!!
cout << "read g: " << in.tellg() << endl;
cout << "read p: " << in.tellp() << endl;
in.seekp(0, ios_base::beg);
in.seekg(0, ios_base::beg);
// tellg() == -1, tellp() == -1 ?????????!!!!!!!!!!
cout << "beg g: " << in.tellg() << endl;
cout << "beg p: " << in.tellp() << endl;
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我会发生什么以及如何解决该问题吗?
对于fstream( std::basic_filebuf),单个文件位置由seekp()和seekg()
不可能独立地跟踪put和get定位。
类模板std::basic_filebuf保存单个文件位置
第 27.9.1.1 节
类 basic_filebuf 将输入序列和输出序列与文件相关联。
读取和写入由类 basic_filebuf 的对象控制的序列的限制与使用标准 C 库文件读取和写入的限制相同。
特别是:
- 如果未打开文件进行读取,则无法读取输入序列。
- 如果文件未打开用于写入,则无法写入输出序列。
- 为输入序列和输出序列维护一个联合文件位置。