# 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);


That line generates a vector subscript out of range exception.

If  I try:

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

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

##### Share on other sites
Rattrap    3385
Additionally, you can move the vector declaration after you have determined the size of the file and pass the size through the constructor.

##### 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  )

##### Share on other sites
noatom    927

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