文件读到链表中,对链表做相关操作,最后重写进文件中
typedef struct student{
int num;
char name[20];
int score;
struct student *next;
}stu;
stu *cre()
{
stu*head = (stu*)malloc(sizeof(stu));
head->next = NULL;
return head;
}
stu* m = cre();
stu *sort(stu*head){
stu*p = head;
stu*q = head->next;
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;
p = head;
q = head->next;
}
return head;
}
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);
p->next = head->next;
head->next = p;
}
stu *del(stu*head){
stu *p, *q;
int n;
printf("请输入要删除学生的学号:\n");
scanf("%d", &n);
q = head;
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");
}
return head;
}
stu *revise(stu*head){
stu *p, *q;
int n;
q = head;
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");
}
return head;
}
stu *find(stu*head){
stu*p;
int n;
p = head;
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");
return head;
}
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;
p = head->next;
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;
readfile(m);
while (1)
{
meau();
printf("请输入命令:\n");
scanf("%d",&a);
switch (a)
{
case 1:sort(m);
break;
case 2:headinsert(m);
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);
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");
}