0

How to read from binary file (bytes, also known as unsigned charin C++) to vector skipping the first value which is number as unsigned int 32, because the first value is also the size of vector?

First value is also the size of the whole file.

7
  • There are a million tutorials on the internet and a million questions on stack overflow dealing with file I/O and storing elements in vectors. Please utilize the search function to find related questions, and then show us some code that you're having trouble with. Commented Apr 2, 2020 at 17:39
  • @JohnFilleau I just don't know how to skip first element in binary file. Commented Apr 2, 2020 at 17:45
  • Try this stackoverflow.com/questions/18640001/… Commented Apr 2, 2020 at 17:47
  • 1
    But you should really be reading the first 4 bytes as a 32 bit uint and using that to reserve space in your vector. en.cppreference.com/w/cpp/container/vector/reserve Commented Apr 2, 2020 at 17:48
  • Yes, I use that value, vector.resize(value). But the rest I have to push in vector, and thank you for the previous comment! Commented Apr 2, 2020 at 17:56

1 Answer 1

2

You could try something like this:

uint32_t data_size = 0;
data_file.read((char *) &data_size, sizeof(data_size));
std::vector<uint8_t> data(data_size);
data_file.read((char *) &data[0], data_size);

The above code fragment first reads the size or quantity of the data from the file.
A std::vector is created, using the quantity value that was read in.
Finally, the data is read into the vector.

Edit 1: Memory-mapped files
You may want to consider opening the data file as a memory mapped file. This is where the Operating System treats the file as memory. You don't have to store the data in memory nor read it in. Since memory mapped file APIs vary among operating systems, you'll have to search your Operating System API to find out how to use the feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.