I am trying to do several exercises to understand the difference between write text and binary files on C, and when looking at results with an hexdump utility I am finding unexpected results. Can you please help me to understand the reason ?
Particularly, I am trying the following code for writing a text file:
#include <stdio.h>
int main() {
FILE *ptr_myfile;
char c = 'a';
int numero = 12345;
ptr_myfile = fopen("test.txt","w");
if (!ptr_myfile){
printf("Unable to open file!");
return 1;
}
fwrite(&c, sizeof(char), 1, ptr_myfile);
fwrite(&numero, sizeof(int), 1, ptr_myfile);
fclose(ptr_myfile);
return 0;
}
When doing a "cat test.txt" I found that the contents of the file are:
cat test.txt
a90
Can not understand how 12345 was converted to 90.
Moreover If I do a
hexdump test.txt
0000000 3961 0030 0000
0000005
On that case, I am findig a first byte written with the value 39. Why ? Second value (61) already matches the ascii value fo 'a'' (61 hex = 97 dec = 'a' ascii code), but can not find a logical explanation for the rest of the bits.
If I change the writing mode to binary file, modifying the line
ptr_myfile=fopen("test.txt","w") by ptr_myfile=fopen("test.txt","wb")
I do not see any change on behavior on the written contents of the file.