【发布时间】:2020-06-19 20:16:35
【问题描述】:
问题场景:有2个文件customer.dat和transaction.dat包含记录数(记录结构在代码定义的bt结构中)。在transacton.dat文件中有2个tran_types(d / c借方或贷方)为每次借记卡和贷记卡都会更新 customer.dat 文件中的余额。
#include<stdio.h>
main()
{
struct tran
{
int accno;
char tran_type;
float amount;
};
struct tran t;
struct cust
{
int accno;
char name[30];
float balance;
};
struct cust c;
FILE *fp,*ft;
fp=fopen("customer.dat","rb+");
if(fp == NULL)
{
printf("Cant open file\n");
exit(1);
}
ft=fopen("transaction.dat","rb");
if(ft == NULL)
{
printf("Error\n");
}
while(fread(&c,sizeof(c),1,fp)==1)
{
rewind(ft);
while(fread(&t,sizeof(t),1,ft)==1)
{
if(c.accno == t.accno)
{
if(t.tran_type=='d')
{
c.balance=(c.balance-t.amount);
fseek(fp,-sizeof(c),SEEK_CUR);
fwrite(&c,sizeof(c),1,fp);
}
else if(t.tran_type =='c')
{
c.balance= (c.balance + t.amount);
fseek(fp,-sizeof(c),SEEK_CUR);
fwrite(&c,sizeof(c),1,fp);
}
}
}
}
fclose(fp);
fclose(ft);
printf("Success");
}
【问题讨论】:
-
你认为 rewind(ft) 函数调用有什么作用?
-
外循环的每次迭代都在内循环使用的文件上调用
rewind。同时,内循环可以调用fseek,在外循环使用的文件上向后移动查找位置。如果这永远循环下去也就不足为奇了。