Question

I'm playing around with binary files in C, and I can't work out one thing - why does the file end in this byte 00001010 (that equals a 10)?

My code is in essence the following (simplified).

FILE *test = fopen("file.b", "ab");
int value = 1;
fwrite(&value, sizeof(int), 1, test);
fclose(test);

After running the program, file.b looks like this (with the help of vim :%!xxd -b).

00000001 00000000 00000000 00000000 00001010

The trailing byte happens independent of the type I choose to write.

Was it helpful?

Solution

10 is a newline. vim automatically appends a newline (if the file didn't end in a newline) when you filter it through xxd.

Since you are treating it as a binary file you should tell vim it is a binary file with vim -b so the newline isn't added automatically.

Take a look at :h binary

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top