c - 整数不写入 C 中的文件

标签 c fwrite

以下代码运行良好,除了我的输出文件不包含整数 10,而是当我在 VIM 中打开它时包含字符 ^@^@^@。如果我在 textedit(在 Mac 上)中打开它,文件似乎是空的。

有人知道我这里哪里出错了吗?

#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);
}

最佳答案

您正在写入二进制数据并期望看到 ASCII。

您可以使用 fprintf 以 ASCII 格式写入数字:fprintf(fp, "%d", x)

关于c - 整数不写入 C 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648592/

相关文章:

C : Compile openSSL project

c - linux子recvfrom没有正常工作

c - _Bool 类型和严格的别名

c - 无法将 linux 程序的输出存储到文件中

c++ - fwrite 4 字符数组,将写入 7 而不是 4

php - PHP 中的 substr_replace 编码

c - 如何将二进制文件中的结构写入另一个二进制文件中的嵌套结构?

php - 将数据写入文件在行尾添加 ^M

c - 画一条线: Problems with the mouse cursor on C Vga graphics

c++ - 在数据写入磁盘之前 fwrite 是否会阻塞?