Question

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 ...

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top