Linux 学生选课管理系统三名学生用户储存数据使用文件系统储存数据的代码是什么
时间: 2024-05-04 10:17:36 浏览: 130
以下是使用C语言实现的一个简单的Linux学生选课管理系统,它使用文本文件来储存学生选课信息的代码示例,其中包含三名学生的信息:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENT_NUM 1000
#define MAX_COURSE_NUM 100
#define MAX_LINE_LENGTH 1024
typedef struct {
char name[64];
int age;
char gender[8];
char id[32];
char major[64];
} student_t;
typedef struct {
char name[64];
int credit;
} course_t;
int read_student_file(student_t *students, const char *filename) {
int count = 0;
char line[MAX_LINE_LENGTH];
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: cannot open file %s\n", filename);
return 0;
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
sscanf(line, "%s %d %s %s %s", students[count].name, &students[count].age, students[count].gender, students[count].id, students[count].major);
count++;
}
fclose(fp);
return count;
}
int read_course_file(course_t *courses, const char *filename) {
int count = 0;
char line[MAX_LINE_LENGTH];
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: cannot open file %s\n", filename);
return 0;
}
while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
sscanf(line, "%s %d", courses[count].name, &courses[count].credit);
count++;
}
fclose(fp);
return count;
}
void write_student_file(student_t *students, int count, const char *filename) {
int i;
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error: cannot open file %s\n", filename);
return;
}
for (i = 0; i < count; i++) {
fprintf(fp, "%s %d %s %s %s\n", students[i].name, students[i].age, students[i].gender, students[i].id, students[i].major);
}
fclose(fp);
}
void write_course_file(course_t *courses, int count, const char *filename) {
int i;
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error: cannot open file %s\n", filename);
return;
}
for (i = 0; i < count; i++) {
fprintf(fp, "%s %d\n", courses[i].name, courses[i].credit);
}
fclose(fp);
}
int main(int argc, char *argv[]) {
student_t students[MAX_STUDENT_NUM];
course_t courses[MAX_COURSE_NUM];
int student_count, course_count;
// 储存三名学生的信息
students[0].age = 20;
strcpy(students[0].name, "张三");
strcpy(students[0].gender, "男");
strcpy(students[0].id, "20190101");
strcpy(students[0].major, "计算机科学与技术");
students[1].age = 21;
strcpy(students[1].name, "李四");
strcpy(students[1].gender, "男");
strcpy(students[1].id, "20190102");
strcpy(students[1].major, "软件工程");
students[2].age = 19;
strcpy(students[2].name, "王五");
strcpy(students[2].gender, "女");
strcpy(students[2].id, "20190103");
strcpy(students[2].major, "信息安全");
student_count = 3;
course_count = read_course_file(courses, "course.txt");
// TODO: 实现选课系统的增删改查功能
write_student_file(students, student_count, "student.txt");
write_course_file(courses, course_count, "course.txt");
return 0;
}
```
在上面的代码中,我们在main()函数中手动储存了三名学生的信息,并在程序结束前将学生和课程信息写回到文本文件中。在实际应用中,可以通过读取用户输入等方式来动态添加学生信息。
阅读全文