Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file into a vector all at once

Tags:

c++

file-io

c++11

Is this a good idea for reading into a std::vector, or is there some gotcha here:

using namespace std;
ifstream file("blah.dat", ios::binary);

vector<T> v(N);

file.read(static_cast<char*>(v.data()), N * sizeof(T));

Does the vector standard allow me to do this to populate a vector? For simplicities sake, let us assume that T is a Plain Old Data Type.

like image 932
Andrew Spott Avatar asked Oct 19 '22 16:10

Andrew Spott


1 Answers

There's no undefined behavior here if T is trivially copyable, which PODs certainly are. vector<T>::data is guaranteed to return a pointer to a contiguous array of vector<T>::size Ts, and the object representation of a trivially copyable type T is guaranteed to be a contiguous sequence of sizeof(T) bytes (possibly including internal padding).

If the bytes you store into that space aren't valid T object representations, you could get undefined behavior when you access them. Exactly which byte sequences constitute a valid T object representation is a bit of a grey area; at the very least you should be able to portably write the underlying bytes of an object of a trivially copyable type to file and successfully read them back into the underlying bytes of an object of the same type.

For paranoia's sake, I'd probably put:

static_assert(std::is_trivially_copyable<T>(),
              "NO NO NO - T MUST BE TRIVIALLY COPYABLE!");

before the file.read for future-proofing.

like image 177
Casey Avatar answered Nov 03 '22 09:11

Casey