C/C++ – binary IO


Here is an example of how we can write to and read from files in binary:

ofstream file(“foo.txt”, ios::out | ios::binary);
unsigned e =101;
file.write(reinterpret_cast<char*>(&e), sizeof(unsigned));

ifstream file(“foo.txt”, ios::in | ios::binary);
unsigned e;
file.read(reinterpret_cast<char*>(&e), sizeof(unsigned));

More info:


One Response to “C/C++ – binary IO”

  1. keramida Says:

    I’m sure this is quite fine for reading in binary mode using C++, but it’s arguably less “noisy” than the plain ANSI C equivalent:

    * Reading an ‘unsigned int’ from a file, in binary mode.

    FILE *fp;
    unsigned int e;

    fp = fopen(“foo.txt”, “rb”);
    if (fp == NULL) {
    /* Error handling code. */
    if (fread(&e, sizeof(e), 1, fp) == 0) {
    /* Nothing read; handle the error. */

    Writing is similarly simple, with the fread() call replace by fwrite().

    In C (as opposed to C++), you don’t have to go through all the hoops to “reinterpret a cast” or similar. That’s, some times, more elegant and fun to read šŸ™‚

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: