c++ – How to read a binary file into a vector of unsigned integer
You are seeking ifs to the end of the file, but you forgot to seek it back to the beginning before calling read(), so there is nothing for read() to read. You need that 2nd seek, eg:
ifstream ifs(INPUT_FILE_NAME,ios::binary);
ifs.seekg(0, ifs.end);
size_t N = ifs.tellg();
ifs.seekg(0, ifs.beg); // <-- ADD THIS!
For that matter, why are you seeking ifs at all? You said the 1st unsigned int in the file tells you the number of subsequent unsigned ints to read, so just read from ifs without seeking it at all, eg:
ifstream ifs(INPUT_FILE_NAME, ios::binary);
uint32_t N = 0;
ifs.read(reinterpret_cast<char*>(&N), sizeof(uint32_t));
vector<uint32_t> buf(N);
ifs.read(reinterpret_cast<char*>(buf.data()), N * sizeof(uint32_t));
In which case, the 1st unsigned int becomes redundant if you are able to remove it, as you could just ask the filesystem for the file’s size, eg:
ifstream ifs(INPUT_FILE_NAME, ios::binary);
vector<uint32_t> buf(filesystem::file_size(INPUT_FILE_NAME) / sizeof(uint32_t));
ifs.read(reinterpret_cast<char*>(buf.data()), buf.size() * sizeof(uint32_t));
Or, simply read from the file until EOF is reached, eg:
ifstream ifs(INPUT_FILE_NAME, ios::binary);
vector<uint32_t> buf;
buf.reserve(filesystem::file_size(INPUT_FILE_NAME) / sizeof(uint32_t));
uint32_t number;
while (ifs.read(reinterpret_cast<char*>(&number), sizeof(uint32_t)) {
buf.push_back(number);
}
Read more here: Source link
