Binary blunder

Something I was trying to figure out at work resulted in writing a make sure I understood how to write an array of numbers to a file. When I loaded the file for viewing it would (in places) be total garbage, and I couldn’t figure out why. I narrowed it down to what seemed to be specific ranges of numbers that were showing up as garbage, and write a new test program:

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

int main()
  FILE *BINfile;
  char *binfilename = "binfile.bin";
  short int data[20];
  int n;

  BINfile = fopen(binfilename, "w+");

  for (n = 0;n < 20; n++)
    data[n] = n;

  fwrite(data, 2, 20, BINfile);


  return 0;

All I’m doing is writing an array containing the numbers 0 through 19 to a file. It still didn’t look right when viewing it (in a program that basically just plots these numbers as a line) so I decided to look at the data in a hex viewer.

hexdumpI’m on a machine that stores bytes as little-endian. To borrow Wikipedia’s example, if I have the decimal number 1000 and I write that to a file as binary data, it gets stored as E8 03. So, I’m expecting my sequence of numbers I’m storing (0 through 19) to be 00 00, 01 00, 02 00, 03 00, and so on up to 19 which is 13 00. I can see 00 00 at the start of my hex dump and 13 00 at the end, but something looks funky in the middle.

Here’s 1 through 9…

hexdump1-9But where I thought 0A 00 would be is this…

hexdump-0d0aWhat’s 0D 0A doing there? And why are the next several numbers wrong?

After much puzzling and Googling I found a StackOverflow post that made me realize that when opening the file for writing I had not specified that it should be written to as a binary file, so it defaulted to a text file. ASCII 10 is a line feed character, which appears to translate to 0D 0A when written to a file.

All I had to do is change this line:

BINfile = fopen(binfilename, “w+”);


BINfile = fopen(binfilename, “w+b”);

Just one little “b” and everything is better.

This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

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

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