求助一个关于fread()函数的读取问题!
这是个修改二进制文件的数据的程序,小弟的疑惑就在于子程序中fread()在 while循环里的是怎么指向下一个结构体的?
#define N 5
typedef struct Student
{
long sno ;
char name ;
float score ;
} STU ;
void fun(char *filename , long sno)
{
FILE *fp ;
STU n ;
int i ;
fp = fopen( filename , " rb+ " ) ;
while(!feof(fp))
{
fread( &n , sizeof( STU ) , 1 , fp ) ;
if( n.sno == sno )
{
break ;
}
}
if( !feof( fp ) )
{
for( i = 0 ; i < 3 ; i++ )
{
n.score += 3;
}
fseek( fp , -( long )sizeof( STU ) , SEEK_CUR ) ;
fwrite( &n , sizeof(STU) , 1 , fp ) ;
}
fclose( fp ) ;
}
int main()
{
STU t = {
{10001,"MaChao", 91, 92, 77},
{10002,"CaoKai", 75, 60, 88},
{10003,"LiSi", 85, 70, 78},
{10004,"FangFang", 90, 82, 87},
{10005,"ZhangSan", 95, 80, 88}
};
STU ss;
int i,j;
FILE *fp;
fp = fopen("student.dat","wb");
fwrite(&t,sizeof(STU),N,fp);
fclose(fp);
printf("\n the original data: \n");
fp = fopen("student.dat","rb");
fread(&ss,sizeof(STU),N,fp);
for( j = 0 ; j < N ; j++ )
{
printf("\nNO:%ld \nNAME:%s \nSCORES:",ss.sno, ss.name);
for( i = 0 ; i < 3 ; i++)
printf("%6.2f",ss.score);
printf("\n");
}
fclose(fp);
fun("student.dat",10003);
printf("\nThe data after modifing:\n");
fp = fopen("student.dat","rb");
fread(&ss,sizeof(STU),N,fp);
for( j = 0 ; j < N ; j++ )
{
printf("\nNO:%ld \nNAME:%-8s \nSCORES:",ss.sno, ss.name);
for( i = 0 ; i < 3 ; i++)
printf("%6.2f",ss.score);
printf("\n");
}
fclose(fp);
return 0;
}
它只管每次读取固定长度的数据,需要我们设置它每次读取的长度
所以设置为 sizeof(STU),也就是每次读一个结构体大小的数据,下一次自动从这次读完的末尾读 明白了!谢谢大佬
页:
[1]