写c代码:文件“stu_info1.txt”包含学生的基本信息(姓名、学号、籍贯三项),现在需 要从该文件中读出信息,并依次为每位学生输入三门课程成绩,计算平均成绩,再将学生 完整信息(姓名、学号、籍贯、课程 1、课程 2、课程 3、平均分)写入文件 “stu_info2.txt”并保存于磁盘上。
时间: 2023-12-03 15:47:45 浏览: 32
以下是实现该功能的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 20
#define MAX_NUM_LEN 15
#define MAX_ADDR_LEN 50
#define MAX_LINE_LEN (MAX_NAME_LEN + MAX_NUM_LEN + MAX_ADDR_LEN + 3)
typedef struct {
char name[MAX_NAME_LEN];
char num[MAX_NUM_LEN];
char addr[MAX_ADDR_LEN];
float score1;
float score2;
float score3;
float avg_score;
} Student;
int main() {
FILE *file_in, *file_out;
char line[MAX_LINE_LEN];
Student student;
// 打开输入文件
file_in = fopen("stu_info1.txt", "r");
if (file_in == NULL) {
printf("Error: Failed to open input file.\n");
return 1;
}
// 打开输出文件
file_out = fopen("stu_info2.txt", "w");
if (file_out == NULL) {
printf("Error: Failed to open output file.\n");
fclose(file_in);
return 1;
}
// 逐行读取学生信息,并计算平均成绩
while (fgets(line, MAX_LINE_LEN, file_in) != NULL) {
sscanf(line, "%s %s %s", student.name, student.num, student.addr);
printf("Enter scores for %s (ID: %s):\n", student.name, student.num);
scanf("%f %f %f", &student.score1, &student.score2, &student.score3);
student.avg_score = (student.score1 + student.score2 + student.score3) / 3;
fprintf(file_out, "%s %s %s %.2f %.2f %.2f %.2f\n",
student.name, student.num, student.addr,
student.score1, student.score2, student.score3, student.avg_score);
}
// 关闭文件
fclose(file_in);
fclose(file_out);
printf("Done.\n");
return 0;
}
```
代码的主要思路是先打开输入文件和输出文件,然后逐行读取学生信息并计算平均成绩,最后将完整信息写入输出文件。需要注意的是,代码使用了结构体来保存学生信息,方便进行读写操作。同时,代码中也对文件打开和关闭进行了错误处理,保证程序的稳定性。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)