Ryan Claxton Ryan Claxton - 1 month ago 23
C Question

fread and fwrite a linked list in C

Here is my struct:

struct Car{
char plateNum[10];
char returnDate[7];
int milage;
float income;
struct Car * next;
typedef struct Car Car;

I need to use fwrite and fread to store the value and load back in after. Is there an easy way?


To write a LL to a file

// Be sure to have opened the file in binary mode

Car *x = head;

// Walk the list and write each node.
// No need to write the next field - which happens to be the last one.
//                    v-----------------v size of data before the `next` field
while (x && fwrite(x, offsetof(Car, next), 1, out_stream) == 1) {
  x = x->next;

To read records from a file into a LL and return the head node:

#include <stddef.h>

// Be sure to have opened the file in binary mode
Car *ReadCars(FILE *in_stream) {
  Car Top;
  Top.next = NULL; // code only uses the `next` field of Top

  Car *previous = &Top;
  Car x;

  // While another record was successfully read ...
  while (fread(&x, offsetof(Car, next), 1, in_stream) == 1) {
    // Fill the next field
    x.next = NULL;

    // Allocate space and copy
    previous->next = malloc(sizeof *(previous->next));
    *(previous->next) = x;

    // Advance to the next
    previous = previous->next;
  return Top.next;