|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这是个修改二进制文件的数据的程序,
小弟的疑惑就在于子程序中 fread()在 while 循环里的是怎么指向下一个结构体的?
#define N 5
typedef struct Student
{
long sno ;
char name[10] ;
float score[3] ;
} 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[i] += 3;
}
fseek( fp , -( long )sizeof( STU ) , SEEK_CUR ) ;
fwrite( &n , sizeof(STU) , 1 , fp ) ;
}
fclose( fp ) ;
}
int main()
{
STU t[N] = {
{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[N];
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[j].sno, ss[j].name);
for( i = 0 ; i < 3 ; i++)
printf("%6.2f",ss[j].score[i]);
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[j].sno, ss[j].name);
for( i = 0 ; i < 3 ; i++)
printf("%6.2f",ss[j].score[i]);
printf("\n");
}
fclose(fp);
return 0;
}
它只管每次读取固定长度的数据,需要我们设置它每次读取的长度
所以设置为 sizeof(STU),也就是每次读一个结构体大小的数据,下一次自动从这次读完的末尾读
|
|