halexh
halexh

Reputation: 3121

sizeof(int) is 4 bytes but only two are written

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?

Upvotes: 4

Views: 221

Answers (3)

Kovi
Kovi

Reputation: 91

I assume that you want to write the number to the file in a binary form. Change a line:

fprintf(fp, "%d", 14);

To:

int i = 14;
fwrite(&i, sizeof(int), 1, fp);

Be sure to read the man page for fwrite. Be aware of that if you have x86 or AMD64 CPU, your bytes will be written in little endian order. If you wanted to be sure that the file will be read always in right byte order, you have to first convert the number using htonl function from header <arpa/inet.h>. And when you read the number again using fread then you have to convert it back using ntohl.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613192

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);

Upvotes: 8

Yu Hao
Yu Hao

Reputation: 122433

fprintf(fp, "%d", 14);

You are writing 14 as a string, that's why you see the text 31 34 in hex form, which are ASCII for the character '1' and '4'.

Upvotes: 4

Related Questions