Integers not writing to file in C
The following code runs fine, except my output file does not contain the integer 10, but instead the characters ^@^@^@ when I open it up in VIM. If I open it in textedit (on the mac) the file appears to be empty.
Does anybody know where I am going wrong here?
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 256
#define MAX_NAME 30
int main() {
FILE *fp;
char fname[MAX_NAME] = "test1.dat";
int x =10;
int num= 0;
if( (fp =fopen(fname, "w")) == NULL) {
printf("\n fopen failed - could not open file : %s\n", fname);
exit(EXIT_SUCCESS);
}
num= fwrite(&x, sizeof(int), 1, fp);
printf("\n Total number of bytes writt开发者_运维问答en to the file = %d\n", num);
fclose(fp);
return(EXIT_SUCCESS);
}
You're writing binary data and expecting to see ASCII.
You could write the number in ASCII using fprintf
: fprintf(fp, "%d", x)
Your code is writing the binary representation of the four bytes 0x0000000a
to the file, i.e. ^@^@^@\n
To write in ASCII, use fprintf
instead.
You wrote the binary bytes of the integer to your file, so that's what you've got.
If you want to see a textual '1', use sprintf
. Binary files often look empty or strange in text editors.
You're writing binary data and expecting ASCII?
If you wish to write formatted data, you can use e.g. the fprintf() function instead of fwrite().
You're opening your file in binary, so basically, you're writing the ascii character 10, not the number 10. Depending on what you want to do, you can open in text mode, use fprintf...
精彩评论