Hi,

I am having a hard time finding the cleanest solution for the following problem.

I want to read a binary file into an std::vector.

Checking online I found the following solution:

Code:

ifstream infile(filename, std::ifstream::binary);
infile.seekg(0, infile.end); //N is the total number of doubles
N = infile.tellg();
infile.seekg(0, infile.beg);
std::vector<double> buf(N / sizeof(double));// reserve space for N/8 doublesinfile.read(reinterpret_cast<char*>(buf.data()), buf.size()*sizeof(double));

which works just fine if my data is an array of doubles, but that can generate problems when used with user defined structs. In particular problems may arise because of a mismatch in the alignment of the data in the binary file and in the vector.

In particular my binary file contains an array of the following type:

Code:

struct NormalizedPair
{
uint32_t ID1;
uint32_t ID2;
double distance;
NormalizedPair()=default;
NormalizedPair(uint32_t id1, uint32_t id2, double d): ID1(id1), ID2(id2), distance(d) {}
};

Is there a universal approach to solve this?

should I use a dedicated library? I am handling large binary files (~tens of GB),

I looked everywhere but cannot find a 100% correct solution for what it seems a trivial problem of loading a file into a container.

Thanks in advance!