用C读和写一个链表



这是我的结构体:

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

我需要使用fwrite和read来存储值并在之后加载。有简单的方法吗?

将LL写入文件

// 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;
}

从文件中读取记录到LL并返回头节点:

#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));
    assert(previous->next);
    *(previous->next) = x;
    // Advance to the next
    previous = previous->next;
  }
  return Top.next;
}

下面的代码是我即兴编写的,还没有经过测试,所以可能需要调整。也请注意;由于时间原因,我没有测试fwritefread的返回值,也没有检查读取错误。你应该这么做。

写入文件

int length = lengthOfList(bar); // Assuming you've already created bar as a linked list of Cars
Car foo[length];
putLinkedListIntoArray(&bar, foo); 
FILE* fh = NULL;
if((fh = fopen("filename", "wb")) == NULL) {
    // Error and die
}
fwrite(&length, sizeof(int), 1, fh);
fwrite(bar, sizeof(Car), length, fh);
fclose(fh);

读取文件

FILE* fh = NULL;
if((fh = fopen("filename", "rb")) == NULL) {
    // Error and die
}
int length;
fread(&length, sizeof(int), 1, fh);
Car foo[length];
fread(foo, sizeof(Car), length, fh);
fclose(fh);
relinkCarList(foo, length);
<标题> 功能
int lengthOfList(Car* start) {
   int length;
   for(length = 0; start->next != NULL; length++) {
       start = start->next;
   }
   return length;
}
void putLinkedListIntoArray(Car* start, Car* array) {
   for(int i = 0; start->next != NULL; i++) {
       array[i] = *start;
       start = start->next;
   }
}
void relinkCarList(Car* array, int length) {
   for(int i = 0; i < length; i++) {
       if(i < length - 1) {
           array[i].next = array[i + 1].next;
       }
   }
}

相关内容

  • 没有找到相关文章

最新更新