编写以下程序:以文本“写”方式打开文本student1.txt文件,调用函数outputToFile,将这5个同学的信息存入student1.txt 文本文件,关闭该文件; 注:函数outputToFile输入参数为student_info、5和已打开的文件指针fp。 ⑤以文本“读”方式打开文本 student1.txt 文件,调用函数inputFromFile,将这5个同学的信息读入并存放到结构体数组student_info1中,关闭该文件;
时间: 2024-03-22 20:37:05 浏览: 74
以下是该程序的实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int age;
float score;
};
void outputToFile(struct student student_info[], int n, FILE *fp) {
int i;
for (i = 0; i < n; i++) {
fprintf(fp, "%s %d %.1f\n", student_info[i].name, student_info[i].age, student_info[i].score);
}
}
void inputFromFile(struct student student_info[], int n, FILE *fp) {
int i;
for (i = 0; i < n; i++) {
fscanf(fp, "%s %d %f", student_info[i].name, &student_info[i].age, &student_info[i].score);
}
}
int main() {
FILE *fp;
struct student student_info[5] = {
{"Tom", 18, 90.5},
{"Jerry", 19, 85.0},
{"Bob", 20, 92.5},
{"Alice", 21, 88.0},
{"John", 22, 95.5}
};
struct student student_info1[5];
int i;
fp = fopen("student1.txt", "w");
if (fp == NULL) {
printf("Cannot open file.\n");
exit(1);
}
outputToFile(student_info, 5, fp);
fclose(fp);
fp = fopen("student1.txt", "r");
if (fp == NULL) {
printf("Cannot open file.\n");
exit(1);
}
inputFromFile(student_info1, 5, fp);
fclose(fp);
for (i = 0; i < 5; i++) {
printf("%s %d %.1f\n", student_info1[i].name, student_info1[i].age, student_info1[i].score);
}
return 0;
}
```
程序的输出结果为:
```
Tom 18 90.5
Jerry 19 85.0
Bob 20 92.5
Alice 21 88.0
John 22 95.5
```
阅读全文