0

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 ?
    }
}
NOhs
  • 2,780
  • 3
  • 25
  • 59
  • `is.read(&myVec[0], 12*sizeof(int32_t));` Is this what you are looking for? – Igor Tandetnik Jul 10 '16 at 01:58
  • What do you mean by "the int32_t data"? An int32_t is a C++ type, not a binary data format. – David Schwartz Jul 10 '16 at 01:59
  • You have to know that the byte order of the data written is the same as what you are reading. – stark Jul 10 '16 at 02:01
  • I just saw that this question appeared earlier, don't know why I didn't see it before: http://stackoverflow.com/questions/36506297/reading-and-writing-a-stdvector-into-a-file-correctly-with-iterators – NOhs Jul 10 '16 at 02:01

1 Answers1

1

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148