头歌C语言数据结构实验线性表读写文件SaveList和LoadList
时间: 2024-05-28 12:08:44 浏览: 16
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 线性表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储数据元素
int length; // 线性表的当前长度
} SqList;
// 初始化线性表
void InitList(SqList* L) {
L->length = 0;
}
// 向线性表中插入元素
int ListInsert(SqList* L, int i, int e) {
if (i < 1 || i > L->length + 1) { // 判断 i 的范围是否有效
return 0;
}
if (L->length >= MAXSIZE) { // 判断线性表是否已满
return 0;
}
for (int j = L->length; j >= i; j--) { // 将 i 及其之后的元素后移
L->data[j] = L->data[j - 1];
}
L->data[i - 1] = e; // 插入新元素
L->length++; // 线性表长度加 1
return 1;
}
// 从线性表中删除元素
int ListDelete(SqList* L, int i, int* e) {
if (i < 1 || i > L->length) { // 判断 i 的范围是否有效
return 0;
}
*e = L->data[i - 1]; // 将被删除的元素赋值给 e
for (int j = i; j < L->length; j++) { // 将 i 之后的元素前移
L->data[j - 1] = L->data[j];
}
L->length--; // 线性表长度减 1
return 1;
}
// 读取线性表元素
void ReadList(SqList* L) {
int n, e;
printf("请输入线性表的长度:");
scanf("%d", &n);
printf("请依次输入线性表的元素:");
for (int i = 1; i <= n; i++) {
scanf("%d", &e);
ListInsert(L, i, e);
}
}
// 显示线性表元素
void DisplayList(SqList* L) {
printf("线性表的元素为:");
for (int i = 0; i < L->length; i++) {
printf("%d ", L->data[i]);
}
printf("\n");
}
// 保存线性表到文件中
void SaveList(SqList* L, char* filename) {
FILE* fp = fopen(filename, "wb"); // 以二进制写方式打开文件
if (fp == NULL) {
printf("打开文件失败!\n");
return;
}
fwrite(&L->length, sizeof(int), 1, fp); // 写入线性表长度
fwrite(L->data, sizeof(int), L->length, fp); // 写入线性表元素
fclose(fp); // 关闭文件
printf("保存成功!\n");
}
// 从文件中读取线性表
void LoadList(SqList* L, char* filename) {
FILE* fp = fopen(filename, "rb"); // 以二进制读方式打开文件
if (fp == NULL) {
printf("打开文件失败!\n");
return;
}
fread(&L->length, sizeof(int), 1, fp); // 读取线性表长度
fread(L->data, sizeof(int), L->length, fp); // 读取线性表元素
fclose(fp); // 关闭文件
printf("读取成功!\n");
}
int main() {
SqList L;
InitList(&L);
ReadList(&L);
DisplayList(&L);
SaveList(&L, "list.dat");
InitList(&L);
LoadList(&L, "list.dat");
DisplayList(&L);
return 0;
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)