fp=fopen("Product.dat","rb+");
while (fread(&prod,sizeof (prod),1,fp)==1) {
prod.stockquant = prod.stockquant + prod.stockorderquant;
prod.stockorderquant = 0;
fseek(fp, -sizeof(prod), SEEK_CUR);
fwrite (&prod, sizeof(prod), 1, fp);
}
fclose (fp);
一旦我进入while循环,我就会得到一个无限循环。文件指针是 fp,prod 是一个名为 PRODUCT 的 Struct 实例,stockquant 和 stockorderquant 都是 struct 中的变量。我正在尝试更改 stockquant 和 stockorderquant 的值。这是我为我的项目做的批量更新。我试图在编辑每个产品的 stockquant 和 orderquant 时浏览整个名为 product.dat 的文件。
为什么我得到一个无限循环?当我在检查 prod.id = userinput 的 if 语句中使用它时,此方法似乎有效。
有什么帮助吗?
一些额外的代码:
void batchupdate(void) {
system("cls");
FILE *fp;
int c=0;
gotoxy(20,4);
printf("****Batch Update Section****");
char another='y';
while(another=='y')
{
system("cls");
gotoxy(15,6);
printf("Are you sure you want to Batch update (Press Y or N)?");
if((getch()=='y') || (getch() == 'Y')) {
system("cls");
int pos;
fp=fopen("Product.dat","rb+");
while(fread(&prod,sizeof(prod),1,fp)==1) {
prod.stockquant = prod.stockquant + prod.stockorderquant;
product.stockorderquant = 0;
fseek(fp, -(sizeof(prod)), SEEK_CUR);
fwrite (&prod, sizeof(prod), 1, fp);
getchar();
pos = ftell(fp);
printf("%d",&pos);
}
fclose (fp);
gotoxy(15,16);
printf("Complete");
gotoxy(15,18);
printf("All products stock quantity have been updated. The stock order quantity has been reset");
gotoxy(15,16);
printf("Do you want to modify another product?(Y/N)");
fflush(stdin);
another=getch() ; }
else { if((getch()=='n') || (getch() == 'N')) {
mainmenu();
}
}
}
returnfunction();
}
这就是我列出我的产品的方式(它有效!)(请注意此处显示的订单数量与 stockorderquant 无关
void listproduct(void)
{
int x;
FILE *fp;
system("cls");
gotoxy(1,1);
printf("*********************************Product List*****************************");
gotoxy(2,2);
printf("Name ID Price StockQuant Order Quant Description");
x=4;
fp=fopen("Product.dat","rb");
while(fread(&prod,sizeof(prod),1,fp)==1){
gotoxy(2,x);
printf("%s",prod.prodname);
gotoxy(20,x);
printf("%d",prod.prodid);
gotoxy(26,x);
printf("%.2f",prod.price);
gotoxy(34,x);
printf("%d",prod.stockquant);
gotoxy(46,x);
printf("%d",prod.orderquantity);
gotoxy(59,x);
printf("%s",prod.description);
printf("\n\n");
x++;
}
fclose(fp);
gotoxy(35,25);
returnfunction();
}
我的结构定义如下:
struct PRODUCT
{
int id;
char name[30];
char desc[50];
float price;
int stockquant;
int orderquant;
int stockorderquant;
};
struct PRODUCT prod;