这几天学了文件处理相关的知识,这里用这个例子来结合理解链表和文件处理。
要求:程序运行起来,检测是否存在目标文件,如果存在,读取文件内容,并保存在链表中,再一 一输出,输出结束问是否要更新文件,支持数据修改,数据添加
(这里我用的学生成绩管理系统)。
如果不存在,手动输入,用链表保存到文件中。
实现思路:首先,我先假设这个文件的形式是以学号、姓名、成绩占据每行。
就是这样的:
1
zhangsan
98
2
lisi
90
那么核心就是把文件读取到链表,在以链表形式写入文件。
读取文件写入链表:
f1=fopen(p,"r");
//fscanf函数的作用就是一行行的读取文件,并把文件的值存放在想要存放的值
while(fscanf(f1, "%d%s%d\n", &num_student,name_student,&score_student)!=EOF)
{
new=(struct Student *)malloc(sizeof(struct Student));
new->name=(char *)malloc(128);
new->pnext=NULL;
new->num=num_student;
new->score=score_student;
strcpy(new->name,name_student);
tail->pnext=new;//尾插法
tail=new;
}
fclose(f1);
把链表写入文件:
void Deposit_file(struct Student *p,char *fd,int eo)
{
FILE *fp;
if(eo==1)//eo是检测文件是否存在
{
fp=fopen(fd,"w+");
}
else
{
fp=fopen(fd,"a+");
}
while(p!=NULL)
{
fprintf(fp,"%d\n",p->num);
fprintf(fp,"%s\n",p->name);
fprintf(fp,"%d\n",p->score);
p=p->pnext;
}
}
那么剩下的就简单了 。
下面就把完整代码发出来
(备注:我这个代码运行是基于我的假设文件形式来写的 ,主要是提供一个思路)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
struct Student
{
int num;
char *name;
int score;
struct Student *pnext;
};
void InitStu(struct Student *new,int i)
{
printf("请输入No %d 位学号\n", i+