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:
That’s because the
eofbit will be set, because you reached the end of the file before.