我在我的Debian x64 PC上运行C++程序时遇到了奇怪的行为。
我无法先读取文件,然后写入另一个值,再读取这些值。我阅读了很多信息,包括stackoverflow上的问题,并发现(也是通过实验)我需要同时更改seekp和seekg。我这样做了,一切正常... 直到我从流中读取东西。在读取操作之后,如果我将指针定位到文件开头,然后调用tellg(),tellp(),它们都返回“-1”。
测试代码:
有人能告诉我发生了什么事情,以及我该怎么做才能解决这个问题吗?
我无法先读取文件,然后写入另一个值,再读取这些值。我阅读了很多信息,包括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;
}
有人能告诉我发生了什么事情,以及我该怎么做才能解决这个问题吗?
seekp()/seekg()
将无法工作。你的文件是怎样的,你是否已经检查它是否成功打开? - jrok