DEV Community

Discussion on: Reading and Writing Files in C: Part 4

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch • Edited

I wondered why a text editor would think that the file is binary even though all numbers we wrote can be interpreted as ASCII. But you're right, the text editor complains. It becomes clear when we use xxd to look into the file instead of cat:

$ xxd test
00000000: 4100 0000 4200 0000 4300 0000 0a00 0000 A...B...C.......

We see that each number we wrote resulted in a 4 bytes block, e.g. 65 (dec) == 0x41 (hex) and in the file we see 0x41000000. The reason is the type of the numbers we wrote: int. The size of an int is 4 bytes on 64bit platforms, thus each number requires 4 bytes in the output file.

There's also a type with only 1 byte of size: char. So let's do the same thing again with char instead of int:

#include <stdio.h>

int main(void)
{
    FILE *file = fopen("test", "wb");

    char numbers[4] = { 65, 66, 67, 10 };
    fwrite(numbers, sizeof(char), 4, file);
    fclose(file);
}

Now the output is:

$ xxd test
00000000: 4142 430a ABC.

And now the text editor won't complain anymore.