Question about seekg () ifstream function in C ++?

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, and then move the pointer to the beginning of the file and read it again. I used inFile.seekg(0, ios::beg); to return to the beginning of the file, but it does not work? Can anybody help me? Thanks

+1
source share
3 answers

Before you start the search, you need to clear all error flags, otherwise no operations are performed in the stream:

 inFile.clear(); inFile.seekg(0,std::ios::beg); 

This is because the eof bit will be set because you reached the end of the file earlier.

+14
source

I think you should reset the ifstream by inFile.clear () error flags. Otherwise, he still believes that he has reached the end of the file.

+5
source
 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; } 
-2
source

All Articles