繁体   English   中英

在C中读取并写入链接列表

[英]fread and fwrite a linked list in C

这是我的结构:

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

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

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

暂无
暂无

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

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