文件读出出错,无法正常读出

问题遇到的现象和发生背景

一个商品库存系统 包括文件的读入读出,信息可以正确读入,但无法读出

问题相关代码,请勿粘贴截图

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;
}

运行结果及报错内容

img

我的解答思路和尝试过的方法
我想要达到的结果

你的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;
}