读文件到链表+界面管理

来源:互联网 发布:c语言嵌入式汇编 编辑:程序博客网 时间:2024/06/06 19:19

读文件到链表+界面管理

#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;}