C语言。一个学生结构体,如下所示。 struct stu{ int id;//学号 char name[20];//姓名 int age;//年龄 int score;//成绩 };*函数名称:readFileForStu *函数功能:从文件格式化读取数据 *写入格式:共读取 num行;每行读出一个stu型数据,每个成员变量之间用空格分隔 *形式参数:struct stu*p,指向 stu型一维数组首地址。该数组用于保存文件读取数据 *形式参数:int num,一维数组元素个数,也即读取文件的行数 *形式参数:char filename[],待读取的文件路径及名称 *形式参数:char mode[],文件使用方式 *返回值:无 *| void readFileForStu(struct stu *p, int num, char filename[],char mode[]){ //请编程实现本函数 *函数名称:stdoutForStu *函数功能:向显示器输出显示数据 *输出格式:共输出 num行:每行输出一个stu型数据,每个成员变量之间用空 * *函数名称:stdoutForStu *函数功能:向显示器输出显示数据 *输出格式:共输出num行;每行输出一个stu型数据,每个成员变量之间用空格分隔 *形式参数:struct stu*p,指向 stu型一维数组首地址 *形式参数:int num,一维数组元素个数 *返回值:无 */ void stdoutForStu(struct stu *p, int num)
时间: 2023-08-03 11:04:03 浏览: 44
以下是readFileForStu和stdoutForStu函数的实现代码:
```
#include <stdio.h>
struct stu{
int id;
char name[20];
int age;
int score;
};
void readFileForStu(struct stu *p, int num, char filename[], char mode[]){
FILE *fp;
fp = fopen(filename, mode);
if(fp == NULL){
printf("Failed to open file %s", filename);
return;
}
int i;
for(i = 0; i < num; i++){
fscanf(fp, "%d %s %d %d", &p[i].id, p[i].name, &p[i].age, &p[i].score);
}
fclose(fp);
}
void stdoutForStu(struct stu *p, int num){
int i;
for(i = 0; i < num; i++){
printf("%d %s %d %d\n", p[i].id, p[i].name, p[i].age, p[i].score);
}
}
```
readFileForStu函数用于从文件中读取数据,并将其保存到结构体数组中,stdoutForStu函数用于将结构体数组中的数据输出到显示器上。在readFileForStu函数中,首先打开指定的文件,然后使用fscanf函数从文件中读取数据,并将其保存到结构体数组中。最后关闭文件。在stdoutForStu函数中,使用循环遍历结构体数组,并使用printf函数将结构体中的数据输出到显示器上。