这是我的代码
#include <iostream>
#include <fstream>
using namespace std;
struct a
{
int x;
int b;
};
int main ()
{
ifstream rfile("test.bin", ios::binary);
a ob;
//Reading from the file for the first time works fine.
rfile.read((char*)&ob, sizeof(ob));
while (rfile)
{
cout<<ob.x<<endl;
rfile.read((char*)&ob, sizeof(ob));
}
rfile.seekg(0, ios::beg);
cout<<"G:"<<rfile.tellg()<<endl; //Outputs -1
rfile.read((char*)&ob, sizeof(ob));
while (rfile)
{
cout<<ob.x<<endl;
rfile.read((char*)&ob, sizeof(ob));
}
return 0;
}
输出是
3
1
G:-1
与第一个循环一样,第二个循环也有效,因为即使在使用 seekg() 之后,指针的位置也是 -1。为什么会这样?