fwrite将垃圾值写入文件

use*_*952 1 c fwrite

#include <stdio.h>

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;

}
Run Code Online (Sandbox Code Playgroud)

预期产出

13

但是将垃圾值写入文件.

Mat*_*Mat 5

假设您已经为其分配了内存cust,或者使用了普通的结构而不是指针,那么您将获得一个包含平台上int 13 的二进制表示的文件.比如,记事本中哪些是不可读的.

如果你看一下十六进制编辑器中的输出,你会看到几个零字节和一个0xOD零字节数取决于平台上的整数大小,以及它们是在13字节之前还是之后取决于它的结尾.

如果您想要一个包含13文本的文件,请使用fprintf.

(由于您尚未分配内存,因此您的程序具有未定义的行为,并且可以执行任何操作.)


修复堆栈上的结构:

#include <stdio.h>

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;
}
Run Code Online (Sandbox Code Playgroud)
$ gcc -Wall -std=c99 -pedantic t.c
$ ./a.out 
$ hexdump -C path_to_file 
00000000  0d 00 00 00                                       |....|
00000004
Run Code Online (Sandbox Code Playgroud)

要获取文本文件,请替换为fwrite:

fprintf(fp, "%d", cust.d); // or "%d\nd";
Run Code Online (Sandbox Code Playgroud)

从打开模式中删除"b",因为这是二进制I/O.