C语言用链表编写车位信息:车位编号、车位位置、车位状态等信息,写入文件
时间: 2024-01-24 13:03:37 浏览: 26
好的,我可以给你提供一种可能的实现方式:
首先,我们需要定义一个结构体来表示车位信息:
```c
typedef struct {
int id;
char location[20];
int status;
} ParkingSpace;
```
然后,我们需要定义一些基本的操作函数,如创建一个新的车位信息,更新车位信息等等:
```c
// 创建一个新的车位信息
ParkingSpace* create_parking_space(int id, char* location, int status) {
ParkingSpace* space = (ParkingSpace*)malloc(sizeof(ParkingSpace));
space->id = id;
strcpy(space->location, location);
space->status = status;
return space;
}
// 更新车位信息
void update_parking_space(ParkingSpace* space, char* location, int status) {
strcpy(space->location, location);
space->status = status;
}
```
接下来,我们需要定义一个链表结构体来存储所有的车位信息:
```c
typedef struct Node {
ParkingSpace* space;
struct Node* next;
} Node;
typedef struct {
Node* head;
Node* tail;
int size;
} List;
```
然后,我们需要定义一些基本的链表操作函数,如添加节点,删除节点等等:
```c
// 添加节点
void add_node(List* list, ParkingSpace* space) {
Node* node = (Node*)malloc(sizeof(Node));
node->space = space;
node->next = NULL;
if (list->size == 0) {
list->head = node;
list->tail = node;
} else {
list->tail->next = node;
list->tail = node;
}
list->size++;
}
// 删除节点
void remove_node(List* list, int id) {
Node* node = list->head;
Node* pre_node = NULL;
while (node != NULL) {
if (node->space->id == id) {
if (pre_node == NULL) {
list->head = node->next;
} else if (node->next == NULL) {
pre_node->next = NULL;
list->tail = pre_node;
} else {
pre_node->next = node->next;
}
list->size--;
free(node);
break;
}
pre_node = node;
node = node->next;
}
}
```
最后,我们需要将所有的车位信息写入文件中,以便于程序重启后可以从文件中读取之前的信息:
```c
void write_to_file(List* list, char* filename) {
FILE* fp = fopen(filename, "wb");
Node* node = list->head;
while (node != NULL) {
fwrite(node->space, sizeof(ParkingSpace), 1, fp);
node = node->next;
}
fclose(fp);
}
void read_from_file(List* list, char* filename) {
FILE* fp = fopen(filename, "rb");
if (fp == NULL) {
return;
}
ParkingSpace space;
while (fread(&space, sizeof(ParkingSpace), 1, fp) == 1) {
ParkingSpace* new_space = create_parking_space(space.id, space.location, space.status);
add_node(list, new_space);
}
fclose(fp);
}
```
现在,我们就可以使用上述定义的数据结构和函数来对车位信息进行操作和存储了。