【发布时间】:2016-03-13 04:44:55
【问题描述】:
void displayAllProduct()
{
FILE *filep;
struct Product a;
int id, found=0;
system("clear");
filep=fopen("fileproduct.txt","w+");
printf("===========================================================================================\n");
printf("\t\t Product Details\n\n");
printf("===========================================================================================\n");
printf("ID | Name | Qty. | Price\n\n");
while(1) //infinite loop
{
printf("182");
fread(&a,sizeof(a),1,filep);
printf("184");
if(feof(filep))
{
break; //done
}
printf("%d\t %s\t %d\t %d\n",a.id, a.name, a.qty, a.price);
}
printf("===========================================================================================\n");
fclose(filep);
}
我目前正在尝试为我的 c 编程课程制作购物车,但在尝试查看我的库存时,我不断遇到分段错误。以上是我展示产品的功能。
【问题讨论】:
-
请发帖Minimal, Complete, and Verifiable example。至少,请向我们展示
struct Product的声明。 -
检查
fopen()是否成功,只有打开成功才尝试读取文件。 -
@MikeCAT,在这种情况下,您不需要检查
fopen的返回值,因为OP 是以w+模式打开它。如果文件不存在,它将被创建。 -
您正在以
w+模式打开fileproduct.txt,即用于写作而非阅读。如果要从中读取,请将模式更改为r。 -
@TonyB 我同意,因此我对 fread 文档的建议
标签: c shopping-cart