Problem with reading a binary file into a vector

Started by
3 comments, last by noatom 8 years, 6 months ago

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...

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.

"I can't believe I'm defending logic to a turing machine." - Kent Woolworth [Other Space]

Additionally, you can move the vector declaration after you have determined the size of the file and pass the size through the constructor.

"I can't believe I'm defending logic to a turing machine." - Kent Woolworth [Other Space]

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 )

resize did the job, and yeah, will use the other tips too. thanks!

This topic is closed to new replies.

Advertisement