简体   繁体   English

Fwrite()结构数组到c中的文件

[英]Fwrite() array of structs to file in c

fwrite() does not match input from array of structs. fwrite() 与来自结构数组的输入不匹配。

Tried: binary files, printing fields of struct elements prior to 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);}

When I later fread, this code does not return what i originally fwrote into the file.当我后来 fread 时,此代码不会返回我最初写入文件的内容。

Your struct contains a pointer to filename , which is an address of data allocated at the time or write.您的结构包含一个指向filename的指针,它是在 time 或 write 分配的数据的地址。 You did not write the string which represents the name, just the pointer to it.你没有写代表名字的字符串,只是写了指向它的指针。

When you read it, your program would read the same pointer, but where does it point to?当你读它时,你的程序会读到同一个指针,但它指向哪里呢? There is probably no string, or it is at a completely different address.可能没有字符串,或者它位于完全不同的地址。 So, you need to make sure that the string is written.因此,您需要确保写入字符串。 The easiest way is to have a char filename[LEN];最简单的方法是有一个char filename[LEN]; as your struct field, where LEN is a big enough number.作为您的结构字段,其中 LEN 是一个足够大的数字。 Otherwise, you need to write the string separately and then restore it as a separate entity.否则,您需要单独写入字符串,然后将其作为单独的实体还原。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM