【发布时间】:2017-04-10 18:01:34
【问题描述】:
以下代码使用 fwrite 将 student 的数据写入文件并使用 fread 读取数据:
struct record
{
char name[20];
int roll;
float marks;
}student;
#include<stdio.h>
void main()
{
int i;
FILE *fp;
fp=fopen("1.txt","wb"); //opening file in wb to write into file
if(fp==NULL) //check if can be open
{
printf("\nERROR IN OPENING FILE");
exit(1);
}
for(i=0;i<2;i++)
{
printf("ENTER NAME, ROLL_ NO AND MARKS OF STUDENT\n");
scanf("%s %d %f",student.name,&student.roll,&student.marks);
fwrite(&student,sizeof(student),1,fp); //writing into file
}
fclose(fp);
fp=fopen("1.txt","rb"); //opening file in rb mode to read particular data
if(fp==NULL) //check if file can be open
{
printf("\nERROR IN OPENING FILE");
exit(1);
}
while(fread(&student.marks,sizeof(student.marks),1,fp)==1) //using return value of fread to repeat loop
printf("\nMARKS: %f",student.marks);
fclose(fp);
}
正如您在输出图像中看到的那样,还打印了具有其他值的标记,而对于所需的输出标记,仅需要具有值 91 和 94 的标记
需要在上述代码中进行哪些更正才能获得所需的输出?
【问题讨论】:
-
你需要回读整个结构。
-
fread(&student.marks,sizeof(student.marks),1,fp)-->fread(&student,sizeof(student),1,fp)
标签: c file-handling fwrite fread