You need to enable JavaScript to run this app. C语言库存系统fscanf读取文件无法同时显示商品名与日期求助
优惠活动
大模型
产品
解决方案
定价
更多

C语言库存系统fscanf读取文件无法同时显示商品名与日期求助

问题根因与解决方法

核心问题点

  • fgets参数错误:调用fgets(inventory_list[i].name, strlen(inventory_list[i].name), ifp);时,name数组未初始化,strlen返回内存中的垃圾值,无法正确限制读取长度。
  • 缓冲区换行残留:fscanf读取数字/%s字符串时不会消耗行尾的换行符,残留的换行符会被后续的fgets直接读取,导致商品名读到空内容。你移除日期读取逻辑时,字段读取顺序的偏移刚好避开了换行残留的影响,所以商品名可以正常显示。
  • 日期缓冲区溢出:date字段仅定义了10个字符长度,示例日期12/21/2019本身已占10位,fscanf读取时自动追加的\0结束符没有存储空间,会触发内存越界,篡改其他字段的值。
  • 数组索引错误:C语言数组下标从0开始,你打印时使用的inventory_list[1]对应的是第二个商品,若文件中只有1个商品会触发越界访问。

修复步骤

  1. 修正结构体date字段长度,至少设置为11位,预留结束符空间
  2. 替换fgets的长度参数为对应数组的sizeof值
  3. 每次fscanf读取后,清空当前行残留的多余内容和换行符
  4. 去除fgets读取到的商品名末尾的换行符
  5. 调整打印的数组下标为0,读取第一个商品信息

修正后代码

结构体定义

struct inventory_item
{
    char name[50];
    int quant;
    double price;
    int id;
    char date[11]; // 修正长度,预留\0存储空间
};
typedef struct inventory_item inventory;

文件读取逻辑

#include <string.h> // 需引入头文件用于字符串操作

{
    FILE *ifp; 
    ifp = fopen(filename, "r");
    if (ifp == NULL) { // 新增文件打开失败判断
        perror("fopen failed");
        return;
    }
    int x = 0;
    fscanf(ifp, "%d",&x);
    // 跳过第一行剩余的注释内容和换行符
    fscanf(ifp, " %*[^\n]");
    for (int i = 0; i < x ; ++i)
    {
        // 修正fgets长度参数
        fgets(inventory_list[i].name, sizeof(inventory_list[i].name), ifp);
        // 移除商品名末尾的换行符
        char *newline = strchr(inventory_list[i].name, '\n');
        if (newline) *newline = '\0';
        
        fscanf(ifp, "%d", &inventory_list[i].quant);
        fscanf(ifp, " %*[^\n]"); // 跳过当前行剩余注释
        
        fscanf(ifp, "%lf", &inventory_list[i].price);
        fscanf(ifp, " %*[^\n]");
        
        fscanf(ifp, "%d", &inventory_list[i].id);
        fscanf(ifp, " %*[^\n]");
        
        fscanf(ifp, "%s", inventory_list[i].date);
        fscanf(ifp, " %*[^\n]");
    }
    fclose(ifp); // 新增文件关闭操作,避免资源泄漏
}

打印逻辑

// 下标改为0对应第一个商品
printf("%s",inventory_list[0].name);
printf(" %d \n %.2lf \n %d \n %s ", inventory_list[0].quant,inventory_list[0].price,inventory_list[0].id,inventory_list[0].date);

内容的提问来源于stack exchange,提问作者Gaston Lee Traub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 17:45:03