c - Fwrite() 将结构数组写入 c 中的文件

标签 c arrays struct

fwrite() 与结构数组的输入不匹配。

尝试:二进制文件,在 fwrite 之前打印结构元素的字段。

FILE *currentPartition;

    struct FAT {
    char *filename;
    int file_length;
    int blockPtrs[10];
    int current_location;       
    } fat[20];`

    for (int i=0;i<20;i++)
     {
      printf("Appending fat index: %d\n",i);
      printf("filename: %s\n",fat[i].filename);
      printf("file length: %d\n",fat[i].file_length);

      printf("current location: %d\n",fat[i].current_location);

      fwrite(fat,sizeof(struct FAT),1,currentPartition);}

当我后来阅读时,这段代码不会返回我最初写入文件的内容。

最佳答案

你的结构体包含一个指向filename的指针,它是当时分配或写入的数据的地址。您没有编写代表名称的字符串,而只是编写了指向它的指针。

当你读取它时,你的程序会读取相同的指针,但它指向哪里?可能没有字符串,或者它位于完全不同的地址。因此,您需要确保字符串已写入。最简单的方法是使用 char filename[LEN]; 作为结构字段,其中 LEN 是一个足够大的数字。否则,您需要单独编写字符串,然后将其恢复为单独的实体。

关于c - Fwrite() 将结构数组写入 c 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55699210/

相关文章:

c++ - 如果继承,则无法使用初始化列表初始化结构?

将值分配给结构中的地址时出现 C 段错误

c - 通过 ssh 替换并打开 stdin/stdout

c - C 问题中的泛型编程

arrays - 将数据从文件读取到数组中以在 Perl 脚本中进行操作

javascript - 如何用高阶函数解决这个问题?

c# - 重构具有内部静态属性的结构

c - 在 Windows 上将 select() 与 STDIN 一起使用?

C:永远不会返回语句

arrays - 编译错误: ByRef arugment type mismatch: How to call a value in an array