fwrite将垃圾值写入文件
#include struct struct_type { int d; }; int main() { struct struct_type *cust; cust->d=13; FILE* fp; fp = fopen("path to file", "wb+"); or, fp = fopen("path to file", "w+"); fwrite(cust, sizeof(struct struct_type), 1, fp); fclose(fp); return 0; }
预期产出
13
但是将垃圾值写入文件。
假设您已经为cust
分配了内存,或者使用了普通的结构而不是指针,那么您将得到一个包含平台上int 13的二进制表示的文件。 比如,记事本中哪些是不可读的。
如果你看一下hex编辑器中的输出,你会看到几个零字节和一个0xOD
– 零字节数取决于平台上的整数大小,以及它们是否在13字节之前或之后取决于在它的字节序上。
如果您想要一个包含13
作为文本的文件,请使用fprintf
。
(由于您尚未分配内存,因此您的程序具有未定义的行为,并且可以执行任何操作。)
修复堆栈上的结构:
#include struct struct_type { int d; }; int main() { struct struct_type cust; cust.d=13; FILE* fp; fp = fopen("path_to_file", "wb+"); fwrite(&cust, sizeof(cust), 1, fp); fclose(fp); return 0; }
$ gcc -Wall -std=c99 -pedantic tc $ ./a.out $ hexdump -C path_to_file 00000000 0d 00 00 00 |....| 00000004
要获取文本文件,请将fwrite
替换为:
fprintf(fp, "%d", cust.d); // or "%d\nd";
从打开模式中删除“b”,因为这是二进制I / O.
将menory分配给您的结构指针cust
fwrite(cust, sizeof(struct struct_type), 1, fp);
将二进制数据写入文件。
存在的数据是二进制数据,即非垃圾。
如果你想看看它是否正确写入读取对象和打印。
使用fread()
另外明智的是将整数转换为字符串并写入文本文件。
然后你就能看到13。