前言
本文使用的链表为带头结点的双向循环链表为例
其他链表的代码可仿照本文操作进行改写
提示:本文省略了很多基础内容,如果读者拥有一定的链表操作基础和文件操作基础会更容易理解学习
一、文件的读取和写入
1.文件内容写入链表中
例如:
在lizi.txt文件中有以下内容
小明 18 123456
小王 19 132456
小张 19 142356
我们要把以上内容添加到链表中,先定义链表结构体如下:
typedef struct Listnode
{
char name[20];
int age;
char phone[20];
struct Listnode* next;
struct Listnode* prev;
}Listnode;
然后在此子函数中将文件内容读取到链表中
用到的文件操作函数是fscanf用于读取文件内容
void Listfp(Listnode* plist, FILE* fp)//将链表和文件指针传入
{
if ((fp = fopen("lizi.txt", "r")) == NULL)
{
printf("文件打开失败\n");
return;
}
while (1)
{
assert(plist);
Listnode* tail = plist->prev;
Listnode* newnode = BuyListnode();
if (EOF == fscanf(fp, "%s %d %s", newnode->name, &newnode->age,newnode->phone))
break;
tail->next = newnode;
newnode->prev = tail;
newnode->next = plist;
plist->prev = newnode;
}
fclose(fp);
}
运行后结果
2.链表中内容写入到文件
例如:先使用尾插法给链表插入内容
void ListPushback(Listnode* phead)
{
Listnode* tail = phead->prev;
Listnode* newnode = BuyListnode();
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
printf("姓名:"); scanf("%s", &newnode->name);
printf("年龄:"); scanf("%d", &newnode->age);
printf("电话:"); scanf("%s", &newnode->phone);
}
然后通过下面的的函数将链表中的内容写入到文件中
使用的文件操作函数为fprintf用于写入文件
void Listfpwrite(Listnode* plist)
{
FILE* fp;
fp = fopen("lizi.txt", "w");
Listnode* cur = plist->next;
do
{
fprintf(fp, "%s %d %s\n", cur->name,cur->age, cur->phone);
cur = cur->next;
} while (cur != plist);
fclose(fp);
}
下面录入两个数据:
在文件中的结果为: