- #include <stdio.h>
- #include <stdlib.h>
- typedef struct student
- {
- char name[30]; char sex;
- int age;
- float score;
- }STU;
- typedef struct node
- {
- struct student data;
- struct node *next;
- }Node;
- void init()
- {
- STU stu[5] =
- {
- {"zhangsan",'s',12,99.4},
- {"lisi",'x',34,34.5},
- {"wangwu",'a',23,45.6},
- {"zhaoliu",'b',23,89.0},
- {"bob",'s',89,23.7}
- };
- FILE * fp = fopen("stu.data","w");
- fwrite(stu,sizeof(STU),5,fp);
- fclose(fp);
- }
- Node *createListFromFile()
- {
- Node *head = (Node*)malloc(sizeof(Node));
- head->next = NULL;
- FILE *fp = fopen("stu.data","r");
- if(fp == NULL) return -1;
- Node * cur = (Node*)malloc(sizeof(Node));
- while(fread(&cur->data,sizeof(STU),1,fp)>0) {
- cur->next = head->next; head->next = cur;
- cur = (Node*)malloc(sizeof(Node)); }
- free(cur);
- return head;
- }
- void displayStudent(Node * head)
- {
- head = head->next;
- while(head)
- {
- printf("%10s\t%c\t%d\t%g\t \n",
- head->data.name, head->data.sex,
- head->data.age,head->data.score);
- head = head->next;
- }
- }
- void insertStudent(Node *head)
- {
- Node * cur = (Node*)malloc(sizeof(Node));
- printf("name:");
- scanf("%s",cur->data.name);
- getchar();
- printf("sex:");
- scanf("%c",&cur->data.sex);
- printf("age:");
- scanf("%d",&cur->data.age);
- printf("score:");
- scanf("%f",&cur->data.score);
-
- cur->next = head->next;
- head->next = cur;
- }
- void deleteStudent(Node *head)
- {
- printf("input student name:");
- char buf[30];
- scanf("%s",buf);
- Node * pfind = head;
- while(pfind != NULL)
- {
- if(strcmp(pfind->data.name,buf) == 0)
- break;
- pfind = pfind->next;
- }
- if(pfind == NULL) printf("find none\n");
- else{
- while(head->next != pfind) head = head->next;
- head->next = pfind->next;
- free(pfind);
- }
- return ;
- }
- void saveStudent2File(Node *head)
- {
- FILE *fp = fopen("stu.data","w");
- head = head->next;
- while(head != NULL)
- {
- fwrite(&head->data,sizeof(STU),1,fp);
- head = head->next;
- }
- fclose(fp);
- }
- int main(void)
- {
- // init();
- Node * head;
- head = createListFromFile();
-
- int choice;
- while(1)
- {
- system("cls");
- displayStudent(head);
- printf("1->insert \t2->delete\t3->exit\t\n"); scanf("%d",&choice);
- switch(choice)
- {
-
- case 1: insertStudent(head); break;
-
- case 2: deleteStudent(head); break;
-
- case 3: saveStudent2File(head); return 0;
-
- default:
- break;
- }
- }
-
- return 0;
- }
复制代码
这个你可以看看, 看不明白就不用看了. 你会了老师才觉得奇怪 |