c语言学生信息用文件保存
时间: 2024-08-12 19:10:29 浏览: 23
在C语言中,为了保存学生信息到文件,通常会使用文件操作的功能,包括文件的打开、写入、关闭等步骤。以下是一个简单的示例,展示如何存储和读取包含学生姓名和成绩的基本信息:
1. 存储学生信息(写入文件):
```c
#include <stdio.h>
#include <stdlib.h>
// 定义学生结构体
typedef struct {
char name[50];
int score;
} Student;
// 写入函数
void saveStudentToFile(Student student, char* filename) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file.\n");
return;
}
fprintf(file, "%s %d\n", student.name, student.score);
fclose(file);
}
// 示例使用
int main() {
Student john;
john.name = "John Doe";
john.score = 90;
saveStudentToFile(john, "students.txt");
return 0;
}
```
2. 读取学生信息(从文件读取):
```c
void loadStudentFromFile(Student* student, char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file.\n");
return;
}
fscanf(file, "%[^ ]%d", student->name, &student->score);
fclose(file);
}
int main() {
Student john;
loadStudentFromFile(&john, "students.txt");
printf("Name: %s, Score: %d\n", john.name, john.score);
return 0;
}
```