I am testing the following code:
int _tmain(int argc, _TCHAR* argv[])
{
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error开发者_开发知识库
}
while (inFile >> x) {
cout << x << endl;
}
cout << "-----------------------------" << endl;
// Reading from beggining file again
inFile.seekg(0, ios::beg);
while (inFile >> x) {
cout << x << endl;
}
inFile.close();
return 0;
}
In the above code, I want to read the file then moving the pointer to the beginning of the file and read again.
I have used inFile.seekg(0, ios::beg);
to get back to the beginning of the file but it does not work?
Can anyone help me, please?
Thanks
Before you seek to the beginning, you need to clear all error flags, else no operations are done on the stream:
inFile.clear();
inFile.seekg(0,std::ios::beg);
That's because the eof
bit will be set, because you reached the end of the file before.
I think you have to reset the error flags of the ifstream by inFile.clear(). Otherwise it still thinks it has reached the end of file.
int autoinc() //auto incriment no//
{
fstream fp;
fp.open("birthreg.dat",ios::in);
fp.seekg(0,ios::beg) ; **//what used this function**
int t=0;
while(fp.read((char*)&st,sizeof(birthreg)))
t=reg_no;
fp.close();
return t;
}
精彩评论