2
#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;

}

预期产出

13

但是将垃圾值写入文件。

4

2 回答 2

6

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

如果您在十六进制编辑器中查看输出,您会看到一些零字节和一0xOD- 零字节的数量取决于您平台上整数的大小,它们是在 13 字节之前还是之后取决于它的字节顺序。

如果您想要一个包含13as 文本的文件,请使用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;
}
$ gcc -Wall -std=c99 -pedantic t.c
$ ./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。

于 2013-10-05T09:24:55.037 回答
2

为结构指针分配内存cust

fwrite(cust, sizeof(struct struct_type), 1, fp);

将二进制数据写入文件。

存在的数据是二进制数据,即不是垃圾。

如果您想查看它是否正确写入对象并打印。

利用fread()

否则将整数转换为字符串并写入文本文件。

然后你可以看到13。

于 2013-10-05T09:25:09.720 回答