Jump to content
  • Advertisement
Sign in to follow this  

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

This topic is 4260 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
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.

Share this post

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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!