Reputation: 15
Fwrite unformated data writes un expected interger? please help me to understand why i am getting 90 in below code?
#include<stdio.h>
int main()
{
int i=12345;
FILE *fp;
fp=fopen("data","w");
fprintf(fp,"%d",i);// 12345 good
fwrite(&i,4,1,fp);// why 90? i am aspecting 12345 in file data?
fwrite(0,4,1,fp);//12345 good
}
Upvotes: 0
Views: 43
Reputation: 11706
fwrite
is writing the raw bytes that represent the integer 12345 to your file.
Assuming int
is 32 bits, this number is 0x00003039
in hex. Assuming a little-endian platform, this writes out the bytes 0x39
, 0x30
, 0x00
, 0x00
. Assuming ASCII encoding, 0x39
is the ASCII code for the character '9'
, and 0x30
for the character '0'
, thus you see 90
in your file.
The other two 0x00
bytes are either being ignored or replaced with spaces by whatever you're using to visualize the file.
Upvotes: 4