Monday, May 29, 2006

C - Premature end-of-file (EOF)

So there I was writing a C program on Windows to change some fields in a binary file and copy the rest over as is. The problem was that the output file was always smaller than the input file? A little research showed that the problem was a 0x1A in the file. This is interpreted as an EOF.

Aside: This dates from MS-DOS days. The ASCII character 0x1A or 26 decimal (the "SUB") character was used as the end of file marker for text files. This mode also translates "\r\n" to "\n" for reading and translates "\n" to "\r\n" for writing.

The solution is to read and write the file as binary i.e.

fopen ("File", "rb") or fopen ("File", "wb") where the "b" indicates binary.

Enjoy!

1 comment:

Anonymous said...

Thanks a lot! I spent several hours trying to figure out why the hell a binary-file reading library (got it from a colleague) works on my Mac, but not on a PC. After quite a while I pinpointed the problem down to the 0x1A character, and then I found your comment. You saved my day!

Lukas