/* file name: slist.c */
/* 单向键结链表,插入、删除使用排序 */
//学会对文件操作文件操作和单链表一起使用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
void read_func(void);
void write_func(void);
void insert_func(void);
void sort_func(void);
void delete_func(void);
void display_func(void);
void modify_func(void);
void anykey_func(void);
struct student
{
char name[20];
int score;
struct student *next;
};
struct student *ptr, *head, *current, *prev;//全部声明为全局变量
int main(void)
{
char option1;
system("cls");//清屏
read_func();
while(1)
{
printf("****************************************\n");
printf(" 1.insert\n");
printf(" 2.delete\n");
printf(" 3.display\n");
printf(" 4.modify\n");
printf(" 5.quit\n");
printf("****************************************\n");
printf(" Please enter your choice (1-5)...");
option1=getche();
printf("\n");
switch(option1)
{
case '1':
insert_func();
break;
case '2':
delete_func();
break;
case '3':
display_func();
break;
case '4':
modify_func();
break;
case '5':
// write_func();
exit(0);//这里也处理的比较好
}
}
}
void read_func(void)
{
FILE *fptr;
head=(struct student *) malloc(sizeof(struct student));
head->next = NULL;
/* 开始时,若表中不存在数据,则要求输入第一笔数据 */
if((fptr=fopen("slist.dat","r")) == NULL)
{
printf(" Data file not exist\n");
printf(" Press any key to edit first record...\n");
getch();
insert_func();//不存在就实行插入操作
}
else
{
ptr=(struct student *) malloc(sizeof(struct student));
while(fscanf(fptr, "%s %d", ptr->name, &ptr->score) != EOF)
{
sort_func();
ptr=(struct student *) malloc(sizeof(struct student));
}
fclose(fptr);
}
}
void write_func(void)
{
FILE *fptr;
fptr=fopen("slist.dat","w");
current=head->next;
while(current != NULL)
{
fprintf(fptr, "%s %d\n", current->name, current->score);
current = current->next;
}
fclose(fptr);
}