Writing binary data to fstream in c++

13,912

Yes you can, this is what std::fstream::write is for:

#include <iostream>
#include <fstream>
#include <cstdint>

int main() {
  std::fstream file;
  uint64_t myuint = 0xFFFF;
  file.open("test.bin", std::ios::app | std::ios::binary);
  file.write(reinterpret_cast<char*>(&myuint), sizeof(myuint)); // ideally, you should memcpy it to a char buffer.
}
Share:
13,912
youR.Fate
Author by

youR.Fate

Electrical Engineer that ocasionally dabbles in code.

Updated on June 05, 2022

Comments

  • youR.Fate
    youR.Fate almost 2 years

    Question

    I have a few structures I want to write to a binary file. They consist of integers from cstdint, for example uint64_t. Is there a way to write those to a binary file that doesn not involve me manually splitting them into arrays of char and using the fstream.write() functions?

    What I've tried

    My naive idea was that c++ would figure out that I have a file in binary mode and << would write the integers to that binary file. So I tried this:

    #include <iostream>
    #include <fstream>
    #include <cstdint>
    
    using namespace std;
    
    int main() {
      fstream file;
      uint64_t myuint = 0xFFFF;
      file.open("test.bin", ios::app | ios::binary);
      file << myuint;
      file.close();
      return 0;
    }
    

    However, this wrote the string "65535" to the file.

    Can I somehow tell the fstream to switch to binary mode, like how I can change the display format with << std::hex?

    Failing all that above I'd need a function that turns arbitrary cstdint types into char arrays.

    I'm not really concerned about endianness, as I'd use the same program to also read those (in a next step), so it would cancel out.

  • youR.Fate
    youR.Fate about 6 years
    That solves part of my problem. I'd like to be able to just use << with my custom fstream. Can I somehow overload << for all (or a set of) cstdint types? Like a template that accepts a predefined list of types?
  • YSC
    YSC about 6 years
    Yes, just define a new type using std::fstream in its implementation, with a templated operator<<.
  • youR.Fate
    youR.Fate about 6 years
    Yes, but can I tell that template to only accept, for example uint64_t, uint16_t and uint8_t, but not for example, std::string, or bool?
  • lmat - Reinstate Monica
    lmat - Reinstate Monica over 3 years
    Yes. Yes you can.