#include <stdio.h> #include <stdlib.h> typedef struct data { int id; //试题编号 char problem[200]; //题干 char optionA[100]; //选项A char optionB[100]; //选项B char optionC[100]; //选项C char optionD[100]; //选项D char ans; //答案 } DATA, *PDATA; typedef struct Node { DATA sd; struct Node *next; //指向下一个试题的指针 } NODE, *PNODE; FILE *_fopen(char *path, char *mode) { FILE *fp = fopen(path, mode); if (fp == NULL) { printf("打开文件失败!\n"); exit(0); } return fp; } void *_malloc(int size) { void *p = malloc(size); if (p == NULL) { printf("分配内存失败!\n"); exit(0); } return p; } void _free(PNODE p) { PNODE q; while (p) { q = p->next; free(p); p = q; } } PNODE _read(char *path) { FILE *fp = _fopen(path, "rb"); DATA sd; PNODE head=NULL, p=NULL; if (fread(&sd,sizeof(DATA),1,fp) == 1) { head = (PNODE)_malloc(sizeof(NODE)); p = head; p->sd = sd; } while (fread(&sd,sizeof(DATA),1,fp) == 1) { p->next = (PNODE)_malloc(sizeof(NODE)); p = p->next; p->sd = sd; } if (p) p->next = NULL; fclose(fp); return head; } void _save(PNODE p, char *path, char *mode) { FILE *fp = _fopen(path, mode); for (; p; p=p->next) fwrite(&p->sd, sizeof(DATA), 1, fp); fclose(fp); } int _input(PDATA pd) { system("cls"); printf("\n**********录入试题*************"); printf("\n请输入试题编号:\n"); scanf("%d", &pd->id); printf("请输入题干:\n"); scanf("%s", pd->problem); printf("请输入选项A:\n"); scanf("%s", pd->optionA); printf("请输入选项B:\n"); scanf("%s", pd->optionB); printf("请输入选项C:\n"); scanf("%s", pd->optionC); printf("请输入选项D:\n"); scanf("%s", pd->optionD); printf("请输入答案:\n"); scanf(" %c", &pd->ans); printf("\n继续录入(Y/N)?"); char choose; scanf(" %c", &choose); while (getchar()!='\n'); return (choose=='Y' || choose=='y'); } void _addData(char *path) { DATA sd; PNODE head, p; head = (PNODE)_malloc(sizeof(NODE)); p = head; while (_input(&p->sd)) { p->next = (PNODE)_malloc(sizeof(NODE)); p = p->next; } p->next = NULL; _save(head, path, "ab+"); _free(head); } void _print(PNODE p) { printf(" 编号: %d\n", p->sd.id); printf(" 题干: %s\n", p->sd.problem); printf("选项A: %s\n", p->sd.optionA); printf("选项B: %s\n", p->sd.optionB); printf("选项C: %s\n", p->sd.optionC); printf("选项D: %s\n", p->sd.optionD); printf(" 答案: %c\n\n", p->sd.ans); } void _display(PNODE p) { for (; p; p=p->next) _print(p); } void _list(char *path) { PNODE head = _read(path); _display(head); _free(head); system("pause"); } int _menu() { int choose=0; do { system("cls"); printf("1.添加\n"); printf("2.显示\n"); printf("0.退出\n"); printf("选择:"); scanf("%d",&choose); } while (choose<0 || choose>2); while (getchar()!='\n'); return choose; } void _proc() { int sel; while (sel=_menu()) { switch(sel) { case 1: _addData("test.dat"); break; case 2: _list("test.dat"); break; default : break; } } } int main(void) { _proc(); return 0; }
[此贴子已经被作者于2018-1-19 06:31编辑过]