一个商品库存系统 包括文件的读入读出,信息可以正确读入,但无法读出
struct goods* load(goods* head) { //从文件中载入商品信息
FILE* fp;
fp = fopen("goodss.txt", "r");
if (fp == NULL) {
printf("不能打开这个文件\n");
exit(0);
}
goods* a = NULL, * cyclic = NULL;
while (!feof(fp)) { //从文件中读入商品
a = (goods*)malloc(sizeof(goods)); //动态内存分配
if (a == NULL) {
printf("Unable to allocate memory");
exit(0);
}
fscanf(fp, "%d%s%f", a->id, a->name, &(a->price));
a->next = NULL;
if (head == NULL) {
head = a;
cyclic = head;
}
else {
cyclic->next = a;
cyclic = cyclic->next;
}
}
fclose(fp);
return head;
}
你的fscanf(fp, "%d%s%f", a->id, a->name, &(a->price));是不是有问题
修改处见注释,供参考:
struct goods* load(goods* head) { //从文件中载入商品信息
FILE* fp;
fp = fopen("goodss.txt", "r");
if (fp == NULL) {
printf("不能打开这个文件\n");
exit(0);
}
goods* a = NULL, * cyclic = NULL;
while (1) { //(!feof(fp)) 修改 //从文件中读入商品
a = (goods*)malloc(sizeof(goods)); //动态内存分配
if (a == NULL) {
printf("Unable to allocate memory");
exit(0);
}
a->next = NULL;
if(fscanf(fp, "%d%s%f\n", &a->id, a->name, &a->price) != 3){ //修改
free(a); //修改
break; //修改
}//修改
if (head == NULL) {
head = a;
//cyclic = head; //修改
}
else {
cyclic->next = a;
//cyclic = cyclic->next; //修改
}
cyclic = a; //修改
}
fclose(fp);
return head;
}