Sign in to follow this  
noatom

Problem with reading a binary file into a vector

Recommended Posts

noatom    927
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
Rattrap    3385
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
Hodgman    51336

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this