• Advertisement
Sign in to follow this  

ifstream: Read() doesn't read the whole file

This topic is 3984 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is my code: std::ifstream File; File.open(pFile, std::ios::in || std::ios::binary); File.seekg(0, std::ios::end); int nLength = File.tellg(); File.seekg(0, std::ios::beg); char *pRaw = new char[nLength]; File.read((char*)pRaw, nLength); int nBytesRead = File.gcount(); File.close(); nLength receives the correct length of the file of 526338(bytes), but after the read-operation, nBytesRead ends up at a value of only 591. Does anybody know what's wrong?

Share this post


Link to post
Share on other sites
Advertisement
std::ifstream file;
file.open(filename, std::ios::in | std::ios::binary);
file.seekg(0, std::ios::end);
std::streamsize length = file.tellg();
if (length != 0)
{
file.seekg(0, std::ios::beg);
std::vector< char > raw(length);
file.read(&raw[0], length);
std::streamsize bytesRead = file.gcount();
}
  • Bitwise or, not boolean or on your openmode flags.
  • tellg returns type std::streamsize.
  • Prefer RAII wrappers (e.g. std::vector) over raw arrays.
  • There is no need to explicity close ifstream objects unless you wish to reuse them. They are RAII wrappers, they clean up after themselves.
  • Hungarian Notation. Ugh.
Σnigma

Share this post


Link to post
Share on other sites
Haha. I can't believe i didn't notice the logical operand. Thanks :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement