Consider the following simple program:
#include <stdio.h>
int main () {
FILE *fp;
printf("sizeof(int)=%d\n", sizeof(int));
fp = fopen("test.bin", "wb");
fprintf(fp, "%d", 14);
fclose(fp);
return 0;
}
It gives the following output to stdout
:
sizeof(int)=4
test.bin has the following contents when viewed in any text editor:
14
When viewed with vi
using the hex dump option (xxd
):
0000000: 3134 0a 14.
When viewed with hexdump -c
:
0000000 1 4 \n
0000003
Obviously an integer on my machine is four bytes, but both hexdump
and vi
are telling me that only two bytes were required to represent 14, and another byte was used to represent the newline character. This is confirmed by the fact that test.bin is only three bytes in size. But, an integer is four bytes, so why are only two bytes representing it?
What obvious fact have I completely forgotten and cant seem to remember?
You have written text to the file. That is what fprintf
does. It converts your parameters into text according to your format string, and then puts that text to the file. You have actually written three bytes to the file: two ASCII digits ('1' and '4') and a line feed ('\n'). Note that 0x31 is the ASCII code for '1'
and 0x34 is the ASCII code for '4'
, and 0x0a is the ASCII code for a line feed.
You need to write binary instead. Use fwrite
for that.
int i = 14;
fwrite(&i, sizeof(i), 1, fp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With