简体   繁体   中英

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 written 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, ie ^@^@^@\\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 eg the fprintf() function instead of fwrite().

您正在以二进制形式打开文件,因此基本上是在编写ascii字符10,而不是数字10。根据您要执行的操作,可以在文本模式下打开文件,请使用fprintf ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM