#include <conio.h> #include <stdio.h> #include <stdlib.h>
#define FILENAME "studentInfo.dat"
struct student { char id[13]; char name[50]; char sex; int age; struct { float c; float en; float math; } grade; };
void show_students(void) { struct student stu; FILE *fp = fopen(FILENAME, "rb"); system("cls"); if (fp == NULL) { puts("文件不存在或打不开!"); getch(); return; }
puts("学号\t\t姓名\t性别\t年龄\tC语言\t英语\t高数"); while (fread(&stu, sizeof(stu), 1, fp)) printf("%-16s%-8s%-8c%-8d%-8.1f%-8.1f%-8.1f\n", stu.id, stu.name, stu.sex, stu.age, stu.grade.c, stu.grade.en, stu.grade.math); fclose(fp);
getch(); }
void add_student(void) { struct student stu; FILE *fp;
system("cls"); printf("请输入学号: "); fflush(stdin); gets(stu.id);
printf("请输入姓名: "); fflush(stdin); gets(stu.name); printf("请输入性别(M或F): "); fflush(stdin); stu.sex = getchar();
printf("请输入年龄: "); scanf("%d", &stu.age);
printf("请输入C语言成绩: "); scanf("%f", &stu.grade.c);
printf("请输入英语成绩: "); scanf("%f", &stu.grade.en);
printf("请输入高数成绩: "); scanf("%f", &stu.grade.math);
fp = fopen(FILENAME, "ab"); if (fp == NULL) puts("录入失败, 文件打不开!"); else { fwrite(&stu, sizeof(stu), 1, fp); fclose(fp); puts("已录入数据!"); } getch(); }
int main(void) { int i = 0; while (i != 3) { system("cls"); printf("1: 查看\n2: 添加\n3: 退出\n请输入: "); scanf("%d", &i); switch (i) { case 1: show_students(); break; case 2: add_student(); break; } } return 0; }
|