简体   繁体   中英

Using fread/fwrite to read and write structures to and from a file in C

I have the following structs:

typedef struct {
  char last[NAMESIZE];
  char first[NAMESIZE];
} name;

typedef struct {
  int id;
  name name;
  float score;
} record;

typedef struct {
  record *data;
  size_t nalloc;
  size_t nused;
} record_list;

I am trying to read records from a file using this function:

int file_read(record_list *list, record* rec)
{
  /* irrelevant code eliminated */

  while(fread(&records, sizeof(record), 1, fp))
  {
    *rec = records;
    valid_list_insert = list_insert(list, rec);
    if(!valid_list_insert)
    {
      return 0;
    }
  }
}

and I am trying to write record_list to a file using this function:

int file_write(record_list* list)
{
  /* irrelevant code eliminated */

  if(fwrite(&list, sizeof(record_list), 1, fp) == 0)
  {
    return 0;
  }
}

However, neither of them work correctly. fread reads in data at, what appears to be, random when I try to display a record_list in my program. And fwrite just writes random characters into a file. Any help on why this isn't working would be greatly appreciated.

Well, one thing that will not work is writing pointers (as in the data member of the record_list ): because (1) it will write the value of the pointer (ie the numeric value of some spot in memory) and (b) you won't allocate your stuff in the same place when you read it back in again. Instead, you will have to carefully parse the structure and record the data in a way that you can get it back again.

This process is called "serialization" (and the reverse is "deserialization"). See also Serialize Data Structures in C .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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