Jump to content
  • Advertisement
Sign in to follow this  
noatom

Problem with reading a binary file into a vector

This topic is 1084 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

std::ifstream file(logFile, std::ifstream::binary);
std::vector<unsigned char> _data;

file.seekg(0, file.end);
int _originalFileSize = file.tellg();
file.seekg(0, file.beg);

_data.reserve(_originalFileSize);
file.read(reinterpret_cast<char*>(&_data[0]), _originalFileSize); 

file.read(reinterpret_cast<char*>(&_data[0]), _originalFileSize);

 

That line generates a vector subscript out of range exception.

 

If  I try:

file.read(reinterpret_cast<char*>(_data.data()), _originalFileSize); 

 

There's no exception but not data gets loaded into the vector. 

 

And yes, the file is not empty, it has over 18 000 bytes worth of data in it...

 

 

 

 

Share this post


Link to post
Share on other sites
Advertisement
Try using resize instead of reserve. Resize will allocate enough usable space, reserve is used to prevent reallocations when using push_back and emplace_back.

[Edit]
Try calling size after you called reserve to see how much space you had available.

Share this post


Link to post
Share on other sites
Additionally, you can move the vector declaration after you have determined the size of the file and pass the size through the constructor.

Share this post


Link to post
Share on other sites

Yeah reserve tells the vector to do some memory allocation ahead of time, but that memory doesn't actually belong to you until you perform push_back/resize.

Just changing reserve to resize should fix it (and add an error check to skip the file.read line if _originalFileSize is zero wink.png )

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!