Search code examples
c++vectorbinaryfiles

How to read from a binary file to an int32_t vector in C++?


I am making a small test seeing if it is feasible to rewrite a very old binary read/write library we use internally. In the code they read a block of memory into a char array and then convert the pointer to an int32_t pointer to access it as an int32_t array.

Question: Is there a way to directly read the int32_t data into a int32_t-vector?

#include <fstream>

using namespace std;

int main()
{
    ifstream is("filename", ifstream::binary);
    if (is) 
    {       
        std::vector<int32_t> myVec(12);  //let's assume that this is indeed the correct size

        //read from is to myVec ?
    }
}

Solution

  • read() can be used:

    is.read( reinterpret_cast<char *>(&myVec[0]), myVec.size() * sizeof(int32_t));
    

    Of course this assumes that the binary data has correct endian-ness, which appears to be the case based on the background information in the question.