Home > Code, HowTo, Samples > How to Read a Binary File in C++

How to Read a Binary File in C++

The following code shows how to read a binary file in C++. This is a quick example and doesn’t contain much error handling and if you’re using Visual Studio, make sure you set the appropriate character set:

Right-click on your project in the Solution Explorer and click Properties.
Select Configuration Properties -> General.
Set the Character Set to Use Multi-Byte Character Set.

///////////////////////////////////////////////////////////////////////////////
// A quick example of reading a binary file in C++.
//
// 2010 Jason Barkes - http://jbarkes.wordpress.com
///////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>

int _tmain(int argc, _TCHAR* argv[])
{
    FILE *file;
    char *fileName;
    int   fileSize;
    char *readBuffer;

    // Set the filename (could also get from a command-line parameter)
    fileName = "c:\\samples\\binary.jpg";

    // Open the specified file in binary mode ("rb")
    file = fopen(fileName, "rb");

    // If the file wasn't opened successfully, print an error and close
    if(file == NULL)
    {
        perror("Failed to open file for read access.");
        return 1;
    }

    // Determine the file size
    fseek(file, 0L, SEEK_END);
    fileSize = ftell(file);
    rewind(file);

    // Allocate the read buffer
    readBuffer = (char *)malloc(fileSize);

    // Read the file's data into the read buffer
    long read = fread(readBuffer, 1, fileSize, file);

    // Do something with the data
    // ...

    // Free allocated memory and close the file
    free(readBuffer);
    fclose(file);

    // Exit program
    return 0;
}

Advertisement
Categories: Code, HowTo, Samples Tags: , ,
  1. September 18, 2011 at 3:58 pm | #1

    Solution more in the spirit of C++

    struct stat a;
    stat(fileName,&a);
    ifstream in(fileName, ifstream::binary);
    scoped_array data(new char[a.st_size]);
    in.read(data.get(), a.st_size);

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.