C语言写入和读取文件

writing and reading into a file in C language

最近我开始在 C 中学习文件 I/O,例如 fopen fwrite 之类的东西。我有一个关于 writing/reading 具有指向文件指针的结构的问题。假设结构看起来像这样

  struct {
  int len;
  int* data;
  }intarr;

len是数组的长度

数据指向一个整数数组。

假设我知道结构是什么(这样我可以稍后读回),我需要将 len 和数据以二进制格式写入文件。但是,如果我只将结构写入文件,则只有指针而不是内容会保存到文件中。

我目前的做法是将数据复制到一个新数组中,然后将len和新数组分别写入文件中。

我不太确定我的方法是否正确。如果它是正确的,你应该如何读回它们?如果不是,当我们想将带有指针的结构的所有内容写入文件以便稍后读取它们时,我们应该做什么?... 我对编程还是个新手,所以如果我说错了,请指正。

了解 serialization & application checkpointing. Read also about files & file systems

您可以 fwrite len 然后数组内容:

 if (fwrite(&intarr.len, sizeof(int), 1, file)) != 1)
   { perror("write length failure"); exit(EXIT_FAILURE); };
 if (fwrite(intarr.arr, sizeof(int), intarr.len, file) != intarr.len)
   { perror("write array failure"); exit(EXIT_FAILURE); };

要读回数据(例如在 rewind(3) 之后或 fopen 编辑 file 之后),首先读取长度然后分配和读取数组:

 if (fread(&intarr.len, sizeof(int), 1, file)) != 1)
   { perror("read length failure"); exit(EXIT_FAILURE); };
 intarr.arr = malloc(sizeof(int)*intarr.len));
 if (!intarr.arr) { perror ("malloc failure"); exit(EXIT_FAILURE); };
 if (fread(intarr.arr, sizeof(int), intarr.len, file) != intarr.len)
   { perror("read array failure"); exit(EXIT_FAILURE); };

另请参阅 flexible array members and about fwrite(3). Notice that stdio file streams maintain a current file position (so data is written in sequence, not overwritten) thant you can query with ftell(3). Some file streams (like on Linux those above pipe(7)-s i.e. from popen(3)) 不可搜索。

在实践中,您可能会以文本格式进行序列化,例如 JSON and/or use a database (e.g. Sqlite, PostgreSQL, MongoDb ....); textual 格式更加便携且更易于调试。由于磁盘可能比 CPU 慢一百万倍,因此值得花一些处理时间在磁盘上组织数据。