Linux 学生选课管理系统储存数据使用文件系统储存数据的代码是什么
时间: 2024-05-04 19:17:35 浏览: 107
使用Linux文件系统储存数据时,需要使用文件读写操作来实现数据的增删改查功能。以下是使用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;
student_count = read_student_file(students, "student.txt");
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;
}
```
在上面的代码中,read_student_file()和read_course_file()函数用于读取学生和课程信息的文本文件,write_student_file()和write_course_file()函数则用于将学生和课程信息写入到文本文件中。在main()函数中,可以实现选课系统的增删改查功能,并在操作完成后将学生和课程信息写回到文本文件中。
阅读全文