Friday, May 04, 2012

ANSI C/C++ fopen behavior

When working with files, although we use C++, we rely on old C file stream processing functions that are under the header <cstdio> on your favorite compiler.

I interface PC applications with hardware and my firmware colleague was telling me that my program that grabs data from the hardware ( the data was supposed to represent a binary file sent by the hardware ) was having a weird behavior. Every 0x0D char was preceded by another 0x0D. I went back check to the low level protocol, the driver functions, the core DLL interface and everything was ok.

Then, I realized every 0x0D in the binary file was like that and the protocol did not gather this sequence of chars. I then went to the application and I realized I wrote something like:

FILE* file = fopen("file.bin", "a" );

By default the compiler will look at this as an ASCII file, unless you specify a "b" char like:

FILE* file = fopen("file.bin", "ab" );

And that was it. The hardware can send me either ASCII files or bin files, but it already produces a binary file that represent the ASCII file so I needed to treat the whole thing as binary.