c语言如何将学生成绩写入文件
时间: 2024-01-30 08:03:58 浏览: 26
通过C语言将学生成绩写入文件的步骤如下:
1. 定义一个结构体来保存学生信息和成绩,例如:
```
typedef struct {
char name[20];
int score;
} Student;
```
2. 打开一个文件,使用fopen()函数,例如:
```
FILE *fp = fopen("scores.txt", "w");
```
3. 将学生信息和成绩写入文件,使用fprintf()函数,例如:
```
Student s = {"Tom", 90};
fprintf(fp, "%s %d\n", s.name, s.score);
```
4. 关闭文件,使用fclose()函数,例如:
```
fclose(fp);
```
完整的代码示例:
```
#include <stdio.h>
typedef struct {
char name[20];
int score;
} Student;
int main() {
FILE *fp = fopen("scores.txt", "w");
if (fp == NULL) {
printf("Failed to open file!\n");
return 1;
}
Student s1 = {"Tom", 90};
Student s2 = {"Jerry", 80};
fprintf(fp, "%s %d\n", s1.name, s1.score);
fprintf(fp, "%s %d\n", s2.name, s2.score);
fclose(fp);
return 0;
}
```