以下代码运行良好,除了我的输出文件不包含整数 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/