小型学籍管理系统C语言代码实现
时间: 2023-10-10 17:13:03 浏览: 102
以下是一个简单的小型学籍管理系统的C语言代码实现,使用了文件存储学生信息:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENT_NUM 50
#define MAX_NAME_LEN 20
typedef struct {
int id;
char name[MAX_NAME_LEN];
int age;
char grade[MAX_NAME_LEN];
} Student;
void print_menu();
int add_student(Student students[], int student_num);
void print_student(Student student);
void print_students(Student students[], int student_num);
void save_students(Student students[], int student_num);
int load_students(Student students[]);
int main() {
Student students[MAX_STUDENT_NUM];
int student_num = load_students(students);
char choice;
do {
print_menu();
scanf(" %c", &choice);
switch (choice) {
case '1':
student_num = add_student(students, student_num);
break;
case '2':
print_students(students, student_num);
break;
case '3':
save_students(students, student_num);
break;
case '0':
printf("退出程序!\n");
break;
default:
printf("输入有误,请重新输入!\n");
break;
}
} while (choice != '0');
return 0;
}
void print_menu() {
printf("欢迎使用学籍管理系统!\n");
printf("1. 添加学生\n");
printf("2. 查看学生\n");
printf("3. 保存学生信息\n");
printf("0. 退出程序\n");
printf("请输入操作编号:");
}
int add_student(Student students[], int student_num) {
if (student_num >= MAX_STUDENT_NUM) {
printf("学生信息已满!\n");
return student_num;
}
Student student;
printf("请输入学生ID:");
scanf("%d", &student.id);
printf("请输入学生姓名:");
scanf("%s", student.name);
printf("请输入学生年龄:");
scanf("%d", &student.age);
printf("请输入学生年级:");
scanf("%s", student.grade);
students[student_num] = student;
printf("添加学生成功!\n");
return student_num + 1;
}
void print_student(Student student) {
printf("ID:%d,姓名:%s,年龄:%d,年级:%s\n", student.id, student.name, student.age, student.grade);
}
void print_students(Student students[], int student_num) {
if (student_num == 0) {
printf("学生信息为空!\n");
return;
}
printf("学生信息如下:\n");
for (int i = 0; i < student_num; i++) {
print_student(students[i]);
}
}
void save_students(Student students[], int student_num) {
FILE *fp;
fp = fopen("students.txt", "w");
for (int i = 0; i < student_num; i++) {
fprintf(fp, "%d %s %d %s\n", students[i].id, students[i].name, students[i].age, students[i].grade);
}
fclose(fp);
printf("学生信息已保存到文件!\n");
}
int load_students(Student students[]) {
FILE *fp;
int student_num = 0;
fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("无法打开文件!\n");
return 0;
}
while (!feof(fp)) {
Student student;
fscanf(fp, "%d%s%d%s", &student.id, student.name, &student.age, student.grade);
students[student_num] = student;
student_num++;
}
fclose(fp);
printf("学生信息已从文件加载!\n");
return student_num;
}
```
这个代码实现使用了结构体存储学生信息,实现了添加学生、查看学生、保存学生信息和从文件加载学生信息等功能。在程序启动时,会从文件中加载学生信息,如果文件不存在,则会创建一个空的学生列表。当用户选择保存学生信息时,学生信息会被保存到文件中。
阅读全文