views:

252

answers:

1

Hi

I'm developping an application under windows, and i'm using fstreams to read and write to the file.

I'm writing with fstream opened like this :

fs.open(this->filename.c_str(), std::ios::in|std::ios::out|std::ios::binary);

and writing with this command

fs.write(reinterpret_cast<char*>(&e.element), sizeof(T));

closing the file after each write with

fs.close()

Reading with ifstream opened like this :

is.open(filename, std::ios::in);

and reading with this command :

is.read(reinterpret_cast<char*>(&e.element), sizeof(T));

The write is going fine. However, i read in a loop this way :

while(!is.eof())
{
  is.read(reinterpret_cast<char*>(&e.element), sizeof(T));
}

and the program keeps reading, even though the end of file should be reached. istellg pos is 0, and gcount is equal to 0 too, but the fail bit and eof bit are both ok.

I'm running crazy over this, need some help ...

+1  A: 

Try this:

while(is.read(reinterpret_cast<char*>(&e.element), sizeof(T))) {}

Also you should open the istream with the binary flag as well:

is.open(filename, std::ios::in | std:ios::binary);

If it reads forever, what does it read? What type is T?

Space_C0wb0y
T is a simple POD type, here something like struct a { WCHAR b[512]; }Your solution works, thank you very much. I really **really** fail to understand while the fail/eof bits are not set though...
raph.amiard
If the answer works and helps you, you should at least accept it (the green tick). You can also vote it up if you think it is a good answer.
Space_C0wb0y
yeah sorry it told me i had to wait 15 secs to vote and i didn't come back in a row.Also i don't have enough rep yet to upvote. But thanks !
raph.amiard