# 学生文件

## 文件读到链表中，对链表做相关操作，最后重写进文件中

``````typedef struct student{

int num;
char name[20];
int score;
struct student *next;
}stu;``````
``````stu *cre()
{

}
stu* m = cre();//全局链表``````
``````stu *sort(stu*head){
//冒泡排序

stu*last = NULL;
int temp;
while (p != last)
{

while (q != last)
{

if (p->num > q->num)
{

temp = p->num;
p->num = q->num;
q->num = temp;
}
p = p->next;
q = q->next;
}
last = p;
}
}``````
``````void headinsert(stu *head)  //头插法
{

stu *p = cre();
printf("输入学号：\n");
scanf("%d", &p->num);
printf("输入姓名：\n");
scanf("%s", p->name);
printf("输入分数：\n");
scanf("%d", &p->score);
}``````
``````stu *del(stu*head){
//根据学号删除
stu  *p, *q;// 带头节点的
int n;
printf("请输入要删除学生的学号：\n");
scanf("%d", &n);
p = q->next;
while (p != NULL&&p->num != n){

q = p;
p = p->next;
}
if (p != NULL){

q->next = p->next;
free(p);
printf("删除成功！\n");
}
else{

printf("没有此人！\n");
}
}``````
``````stu *revise(stu*head){
//根据学号修改
stu *p, *q;
int n;
p = q->next;
printf("请输入要修改的学生的学号：\n");
scanf("%d", &n);
while (p != NULL&&p->num != n){

q = p;
p = p->next;
}
if (p != NULL){

p->num = n;
printf("输入姓名：\n");
scanf("%s", p->name);
printf("输入分数：\n");
scanf("%d", &p->score);
printf("修改成功！\n");
}
else
{

printf("没有此人！\n");
}
}``````
``````stu *find(stu*head){
//yes
stu*p;
int n;
p = p->next;
printf("请输入要查找的学生学号：\n");
scanf("%d", &n);
while (p&&p->num!=n){

p = p->next;
}
if (p)
{

printf("学号：%d\n", p->num);
printf("姓名：%s\n", p->name);
printf("分数：%d\n", p->score);
}
else
printf("没有此人！\n");
}``````
``````void shuchu(stu*haed){
//传指针 输出链表
printf("全部数据：\n");
stu *p;
p = haed->next;
printf("学号\t姓名\t分数\n");
while (p != NULL)
{

printf("%d\t%s\t%d\n", p->num,p->name,p->score);
p = p->next;
}
}``````
``````void sa(stu*head){
//文件
FILE *fp;
if((fp=fopen("abc.txt","w"))==NULL)  //只写方式
{

printf("cuowu打不开文件");
system("pause");
}
stu *p;
while (p != NULL)
{

fprintf(fp,"%d %s %d\n",p->num,p->name,p->score);
p = p->next;
}
fclose(fp);
}``````
``````void readfile(stu*in)//将文件的内容读出并且保存到链表中去
{

FILE*fp;
stu* infor;
infor = (struct student*)malloc(sizeof(student));
infor->name[20] = {
0};
infor->num = 0;
infor->score = 0;
infor->next = NULL;

if ((fp = fopen("abc.txt", "r")) == NULL)
{

printf("cuowu打不开文件");
system("pause");
}
while (fscanf(fp,"%d %s %d\n",&infor->num,infor->name,&infor->score)!=EOF)
{

insert(in,infor);
}
fclose(fp);
printf("文件读取成功！(链表)\n");
}``````
``````int main(int argc, char** argv) {

int a = 0;
while (1)
{

meau();
printf("请输入命令：\n");
scanf("%d",&a);
switch (a)
{

case 1:sort(m);//排序
break;
break;
case 3:del(m); //删除
break;
case 4:revise(m); //修改
break;
case 5:find(m);  //查找
break;
case 6:shuchu(m); //输出
break;
case 7:sa(m);    //保存到文件，w形式打开
exit(0);
break;
}
system("pause");
system("cls");
}
return 0;
}``````
``````void meau()
{

printf("1排序\n");
printf("2添加\n");
printf("3删除\n");
printf("4修改\n");
printf("5查找\n");
printf("6输出\n");
printf("7保存退出\n");//只写方式，文件存在会重写
}``````