Friday, August 6, 2010

C++ Programming: I/O Binary File

Despite of its lots of use, C++ I/O Binary file example is one of the most rare you can google (or bing, or yahoo.. or else). There are samples here and there but its hard to digest and most of the time, its just about reading a binary file, without knowing whats in it.

I built a template for my own to create a C++ I/O Binary, read and write, and with header. I found out that header is very important in every file type. Here is the step that I use:

1. Create your header as struct. You can find out the size of this header by calling sizeof(yourstruct) method.

2. Assuming that header is always on top, read the header first by using this step:

fread(&headers, sizeof(MtexHeader), 1, fp);

This will save the binary from file fp, as big as sizeof(youheader), to a variable named headers. If there is more header, do this repeatedly until you reach the content part.

3. If you already read all the header, you probably have an idea how large the rest of the file is (lets assume sizeOfContent). Imagine the file is a bitmap file, and from the header, you know the width and height. So the next step should be copying the rest of the content to memory.

fread(&content, sizeOfContent, 1, fp);

For a complete working code you can see mine from here. This was built in OS X environment using XCode with GCC 4.0. There you go, how to read binary file with header. its very useful if you want to read image file, or maybe creating your own file format. For other kind of I/O in C++ you can find it here.

No comments: