以单链表为数据结构的一个学生信息输入读取文件程序(尾插法)

#include
#include
struct Node
{
	char name[10];
	int num;
	int age;
	char addr[15];
	struct Node *next;
};
struct Node *creat_inf();//输入数据到单链表
void save_inf(struct Node *h);//把单链表的信息写到文件
struct Node *read_inf();//从文件中读取信息到链表
void print_inf(struct Node *h);//输出到屏幕
main()
{
	struct Node *head;
	head=creat_inf();
	save_inf(head);
	head=read_inf();
	print_inf(head);
}
struct Node *creat_inf()
{
	struct Node *head,*r,*stu;
	int i=0;
	char choice;
	head=(struct Node *)malloc(sizeof(struct Node));
	head->next =NULL;
	r=head;
	do
	{
		stu=(struct Node *)malloc(sizeof(struct Node));
		printf("\n\n第%d个人的信息:\n",++i);
		printf("\n姓名:");
		scanf("%s",stu->name );
		printf("\n学号:");
		scanf("%d",&stu->num );
		printf("\n年龄:");
		scanf("%d",&stu->age );
		printf("\n地址:");
		scanf("%s",stu->addr );
		r->next =stu;
		r=stu;
		printf("Continue?(Y/N)");
		choice=getche();
	}while(choice=='Y'||choice=='y');
	r->next =NULL;
	return (head);
}
void save_inf(struct Node *h)
{
	struct Node *stu;
	FILE *fp;
	char filename[40];
	printf("\n请输入要保存的文件信息:");
	scanf("%s",filename);
	if((fp=fopen(filename,"wt"))==NULL)
	{
		printf("写文件出错,按任意键返回");
		getch();
		exit(1);
	}
	for(stu=h->next;stu!=NULL;stu=stu->next )
	fprintf(fp,"%s %d %d %s\n",stu->name ,stu->num ,stu->age ,stu->addr );
	printf("\n文件已经成功保存,按任意键返回!");
	getch();
	fclose(fp);
}
struct Node *read_inf()
{
	struct Node *head,*r,*stu;
	FILE *fp;
	char filename[40];
	printf("\n请输入要打开的文件名:");
	scanf("%s",filename);
	if((fp=fopen(filename,"rt"))==NULL)
	{
		printf("读文件出错,按任意键返回!");
		getch();
		exit(1);
	}
	head=(struct Node *)malloc(sizeof(struct Node));
	head->next =NULL;
	r=head;
	while(!feof(fp))
	{
		stu=(struct Node*)malloc(sizeof(struct Node));
		fscanf(fp,"%s %d %d %s",stu->name ,&stu->num ,&stu->age ,stu->addr );
		r->next =stu;
		r=stu;
	}
	r->next =NULL;
	fclose(fp);
	printf("\n文件中的信息已经正确读出,按任意键返回!");
	getch();
	return head;
}
void print_inf(struct Node *h)
{
	struct Node *stu;
	printf("\n该班的信息为:\n");
	printf("姓名  学号 年龄  地址\n");
	for(stu=h->next;stu->next !=NULL;stu=stu->next );
	printf("%s %d %d %s\n",stu->name ,stu->num ,stu->age ,stu->addr );
}

你可能感兴趣的:(以单链表为数据结构的一个学生信息输入读取文件程序(尾插法))