Search code examples
c++fileiobinaryfiles

How can I write longs to a binary file in C++?


I have an array of longs, and I want to write each element into a binary file. I know that you use write() to write to a binary, but write() accepts two arguments: a pointer to a char array (the buffer), and a number. Since I have an array of longs, I wasn't able to write using write(). I even tried passing a pointer to the long int array directly into the first argument, but it produced a compiler error.

Here's an example of what I'm trying to do:

long* arr = new long [999999];

// imaginary code that fills arr with data

file.write(arr,1000000);

How can I write my array of longs into a binary file? I've considered somehow converting the longs into chars, but I doubt that would work, and there might be a loss in precision when converting between the data types. In addition, when I compile the code, the compiler error left this note: "no known conversion for argument 1 from 'long int*' to 'const char*'".

Thanks for helping.


Solution

  • No, that's exactly what you should do:

    const size_t N = 999999;
    long* arr = new long[N];
    file.write((const char*)arr, sizeof(long)*N);
    

    This reinterprets your array of longs as a simple sequence of bytes (i.e. chars), and writes that sequence to the file.