#include
#include
#include
#include "list.h"
typedef struct student//创建结构体
{
char buf_name[20];
int age;
int class;
float score;
struct list_head list;
}stu, *st;
st head;
FILE *scr_fp;
st create_head();//创建头节点
st create_new();//创建分节点
void add_stu();//添加学生信息
void view_stu();//查看学生信息
void delete_stu();//删除学生信息
void save_stu();//将文件中的学生信息保存到链表中
void save_file();//将数据保存到文件中
int main(int argc, char const *argv[])
{
head = create_head();
save_stu();
while(1)
{
int n;
printf("1---添加学生信息 2---查看学生信息 3---删除学生信息 4---退出\n");
scanf("%d",&n);
switch(n)
{
case 1 : add_stu();break;
case 2 : view_stu();break;
case 3 : delete_stu();break;
}
if(n == 4)
{
break;
}
}
fclose(scr_fp);
return 0;
}
st create_head()
{
head = malloc(sizeof(stu));
INIT_LIST_HEAD(&head->list);
return head;
}
st create_new()
{
st new = malloc(sizeof(stu));
if(new != NULL)
bzero(&new->list, sizeof(struct list_head));
return new;
}
void save_file()//将数据保存到文件
{
st p;
struct list_head *pos;
list_for_each(pos, &head->list)
{
p = list_entry(pos, struct student, list);
fprintf(scr_fp,"%s %d %d %.2f\n", p->buf_name, p->age, p->class, p->score);
}
}
void save_stu()
{
scr_fp = fopen("1.txt","a+");//以可读可写的方式打开原文件
if(scr_fp == NULL)//判断是否成功打开文件
{
perror("fopen() failed");
return ;
}
while(1)
{
st new = create_new();
fscanf(scr_fp, "%s %d %d %f\n", new->buf_name, &new->age, &new->class, &new->score);//从文件读取数据
//printf("姓名:%s 年龄:%d 班级:%d 成绩:%.2f\n", new->buf_name, new->age, new->class, new->score);
if(feof(scr_fp))//如果读到文件末尾 退出循环
break;
}
}
void add_stu()
{
st new = create_new();
printf("请输入学生信息:姓名 年龄 班级 成绩\n");
scanf("%s%d%d%f", new->buf_name, &new->age, &new->class, &new->score);//输入学生信息
FILE *scr_fp = fopen("1.txt","w+");//以清空,可写的方式打开原文件
if(scr_fp == NULL)//判断是否成功打开文件
{
perror("fopen() failed");
return ;
}
}
void delete_stu()
{
scr_fp = fopen("1.txt","w+");//以清空,可写的方式打开原文件
if(scr_fp == NULL)//判断是否成功打开文件
{
perror("fopen() failed");
return ;
}
st p;
struct list_head *pos, *n;
char buf_del[20];
printf("请输入要删除的学生姓名:\n");
scanf("%s",buf_del);
list_for_each_safe(pos,n,&head->list)
{
p = list_entry(pos,struct student,list);
if(strcmp(p->buf_name,buf_del)==0)
{
list_del(&p->list);
return ;
}
}
printf("未找到该学生信息\n");
}
void view_stu()
{
st p;
struct list_head *pos;
list_for_each(pos, &head->list)
{
p = list_entry(pos, struct student, list);
printf("姓名:%s 年龄:%d 班级:%d 成绩:%.2f\n", p->buf_name, p->age, p->class, p->score);
}
}
list_for_each和list_for_each_safe 两个函数进不去是怎么回事呀