Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why still end of file with ifstream::open(.. 1

Status
Not open for further replies.

hughLg

Programmer
Feb 18, 2002
136
0
0
MY
Isn't once we use open(..) function to open the ifstream file will automatically place the file pointer to the beginning?

Code:
ifstream inF("file.dat", ios::in | ios::binary);
	for (;;) {
		inF.read((char *)&num, sizeof(int));
		if (inF.gcount() == 0)
			break;
		cout << num << endl;
	}
	inF.close();

	ifstream inF("file.dat", ios::in | ios::binary);
	inF.clear();  // ???
	for (;;) {
		inF.read((char *)&num, sizeof(int));
		if (inF.gcount() == 0)
			break;
		cout << num << endl;
	}
	inF.close();

Look at the line with question mark commented out, if this clear() function not exist there, the file cannot be readed out, it is definitely eof reported with the open function. why?
 
Your code won't even compile because you are declaring the same variable name twice.

Normally, clear is used when you are re-using an fstream. So if your code was actually this:
Code:
    ifstream inF("file.dat", ios::in | ios::binary);
    for (;;) {
        inF.read((char *)&num, sizeof(int));
        if (inF.gcount() == 0)
            break;
        cout << num << endl;
    }
    inF.close();

    inF.open("file.dat", ios::in | ios::binary);
    inF.clear();  // ???
    for (;;) {
        inF.read((char *)&num, sizeof(int));
        if (inF.gcount() == 0)
            break;
        cout << num << endl;
    }
    inF.close();

Then the clear() is necessary because the previous bit of code sets a failbit when it can no longer read. Calling close or open doesn't reset the failbit, you have to call clear() explicitly when you re-use a stream.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top