Reputation: 655
I'm having trouble reading a large file into my own buffer in C++ in Visual Studio 2010. Below is a snippet of my code where length is the size of the file I'm reading in, bytesRead is set to 0 before this is run, and file is a std::ifstream.
buffer = new char[length];
while( bytesRead < length ){
file.read( buffer + bytesRead, length - bytesRead );
bytesRead += file.gcount();
}
file.close();
I noticed that gcount() returns 0 at the second read and onwards, meaning that read() did not give me any new characters so this is an infinite loop. I would like to continue to read the rest of the file. I know that the eofbit is set after the first read even though there is more data in the file.
I do not know what I can do to read more. Please help.
Upvotes: 4
Views: 244
Reputation: 500357
Make sure you open your file in binary mode (std::ios::binary
) to avoid any newline conversions. Using text mode could invalidate your assumption that the length of the file is the number of bytes that you can read from the file.
In any case, it is good practice to examine the state of the stream after the read and stop if there has been an error (rather can continue indefinitely).
Upvotes: 3
Reputation: 490138
It sounds like your stream is in a failed state, at which point most operations will just immediately fail. You'll need to clear
the stream to continue reading.
Upvotes: 2