读文件到链表+界面管理
#include "stdafx.h"
#include <stdlib.h>
//数据类型
typedef struct student
{
int num;
char name[30];
char sex;
float math;
float english;
float chinese;
}Stu;
//链表类型
typedef struct node
{
Stu data;
struct node * next;
}Node;
//初始化并写入文件
void init()
{
Stu stu[] = {
{ 1001, "bob", 'x', 100, 30, 20 },
{ 1002, "bob2", 'x', 100, 30, 20 },
{ 1003, "bob3", 'x', 100, 30, 20 }
};
FILE* fp = fopen("stu.data", "wb+");
if (NULL == fp)
exit(-1);
fwrite((void*)stu, sizeof(stu), 1, fp);
fclose(fp);
}
//读文件生成链表
Node *createListFromFile()
{
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
FILE* fp = fopen("stu.data", "rb");
if (NULL == fp)
exit(-1); //申请出错后 退出
Node * cur = (Node*)malloc(sizeof(Node));
//提前申请一个空间来装读取的数据 直接将数据放入链表中
while (fread((void*)&cur->data, sizeof(Stu), 1, fp)>0)
{
cur->next = head->next;
head->next = cur;
cur = (Node*)malloc(sizeof(Node));
//插入一个数据后重新申请一个空间 为下次读取准备
}
free(cur); //无论如何都会多申请一个空间 需要释放
return head;
}
//打印链表中的所有信息
void displayListOfStu(Node *head)
{
head = head->next;
printf("\t\tnum \tname\t sex\tMath\tEng \tChi \n");
while (head != NULL)
{
printf("\t\t%4d\t%5s\t%3c\t%4.2f\t%4.2f\t%4.2f\n",
head->data.num, head->data.name, head->data.sex,
head->data.math, head->data.english, head->data.chinese);
head = head->next;
}
}
//增加链表信息
void addListOfStu(Node *head)
{
Node *node = (Node*)malloc(sizeof(Node));
printf("请输入学号:"); scanf("%d", &node->data.num);
printf("请输入姓名:"); scanf("%s", node->data.name); getchar();
printf("请输入性别:"); scanf("%c", &node->data.sex);
printf("请输入数学:"); scanf("%f", &node->data.math);
printf("请输入英语:"); scanf("%f", &node->data.english);
printf("请输入国文:"); scanf("%f", &node->data.chinese);
node->next = head->next;
head->next = node;
}
//将链表中数据保存到文件中
void saveList2File(Node *head)
{
FILE*fp = fopen("stu.data", "wb");
if (fp == NULL)
exit(-1);
head = head->next; //跳过没用的data数据
while (head != NULL)
{
fwrite((void*)&head->data, sizeof(Stu), 1, fp);
head = head->next;
}
fclose(fp);
}
//删除链表
void deleteListNodeOfStu(Node *head)
{
}
//查找链表
void searchListNodeOfStu(Node *head)
{
}
//菜单选择
void menu()
{
Node *head = createListFromFile(); //开始时自动生成数据
while (1) //一直等待输入操作
{
system("cls"); //刷屏
printf("\t\t\t Student Management Sys\n\n");
displayListOfStu(head); //打印已有数据
printf("\n\t1->add Stu\t2->delete Stu\t3->Search Stu \t4->exit\n");
int choice;
scanf("%d", &choice); //选择功能 进行调用
switch (choice) {
case 1:
addListOfStu(head);
break;
case 2:
deleteListNodeOfStu(head);
break;
case 3:
searchListNodeOfStu(head);
break;
case 4: //保存并退出
saveList2File(head);
exit(1);
break;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//init(); //运行整个程序之前 先init初始化生成相应文件
menu();
return 0;
}