Skip to content

Instantly share code, notes, and snippets.

@grogy
Created March 11, 2013 20:08
Show Gist options
  • Save grogy/5137278 to your computer and use it in GitHub Desktop.
Save grogy/5137278 to your computer and use it in GitHub Desktop.
C++ write to binary file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream out;
out.open("out.bin", ios::out | ios::binary | ios::trunc);
// check open file for write
if (!out.is_open()) {
cerr << "Error in open file './out.bin'" << endl;
return 1;
}
// write integer
// in hex is '6f'
int num = 111;
out.write(reinterpret_cast<const char*>(&num), sizeof(num));
// write char
// in hex is '65'
int ch = 'e';
out.write(reinterpret_cast<const char*>(&ch), sizeof(ch));
// close (write data in buffer to file)
out.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment