|
-
September 13th, 2004, 09:57 AM
#1
Is fucntion ifstream::eof() reasonable?
Please take a look at the code listed below:
const char *cszFilePath = "TestFile";
ofstream ofs;
ofs.open(cszFilePath, ios_base: ut | ios_base::binary);
int iSize = 3;
ofs.write((char *)&iSize, sizeof(int));
ofs.close();
ifstream ifs;
ifs.open(cszFilePath, ios_base::in | ios_base::binary);
int iTemp;
ifs.read((char *)&iTemp, sizeof(int));
bool bEOF = ifs.eof();
Since there is only one integer in the file "TestFile", after reading a integer from the input file stream, bEOF should be true here, but actually its value is FALSE!
Who can explain this to me? Thank you very much for your help!
-
September 13th, 2004, 01:17 PM
#2
Re: Is fucntion ifstream::eof() reasonable?
eof does not work "proactively" (i.e., saying you that the next "read" operation will find the EOF).
It works "reactively", i.e., when you are reading something (using "read" for instance) and you reach the end of file, then eof returns true.
So you can try not using eof() at all (C++ is not VB or Delphi). The function feof from the standard C library also has a similar behaviour, so it's very difficult to find some program written using "feof" (try searching for such a program in Google).
You can try the following code and see that it works (i.e, prints only a single line with the value "3").
Code:
#include <iostream>
#include <fstream>
using namespace std;
main () {
const char *cszFilePath = "TestFile";
ofstream ofs;
ofs.open(cszFilePath, ios_base::out | ios_base::binary);
int iSize = 3;
ofs.write((char *)&iSize, sizeof(int));
ofs.close();
ifstream ifs;
ifs.open(cszFilePath, ios_base::in | ios_base::binary);
int iTemp;
while (ifs.read((char*)&iTemp, sizeof(int))) {
cout << iTemp << endl;
}
}
The explanation is that ifs.read() returns the own "ifs" variable. There is an operator that converts an istream to a boolean; the operator returns false if you've reached the end - of - file, and true if the read operation succeeded..
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|