You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu环境下C语言读取txt文件计算CRC32十六进制代码运行出错求助

问题原因与修复方案

核心错误点

  • 下标越界:读取文件结束后变量i的值为读取到的总行数,后续打印内容、取字符串计算CRC时全部误用i作为下标,访问的是line数组中未初始化的越界区域,直接导致输出为空、CRC值为0
  • 缺少文件打开校验:未判断fopen的返回值,如果input.txt不在程序运行目录、或无读取权限,后续操作都会异常
  • 换行符处理逻辑缺陷:直接将fgets读取到的字符串最后一位置为\0,会误删长度刚好等于LSIZ-1的行的末尾有效字符
  • CRC计算逻辑错误:原逻辑只尝试读取单行计算CRC,无法正确计算整个文件的CRC32值
  • 缺少数组边界判断:原代码未限制读取行数不超过RSIZ,可能出现数组溢出问题

修复后代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define LSIZ 128
#define RSIZ 10

int main()
{
    char *filename = "input.txt";
    FILE *fptr = fopen(filename, "r");
    // 新增文件打开校验
    if (fptr == NULL) {
        perror("打开文件失败");
        return EXIT_FAILURE;
    }

    int i = 0, j;
    char line[RSIZ][LSIZ];
    uLong crc = crc32(0L, Z_NULL, 0); // 初始化CRC32基础值

    // 新增数组边界判断,避免溢出
    while(i < RSIZ && fgets(line[i], LSIZ, fptr) != NULL) {
        // 仅当末尾是换行符时才截断
        int len = strlen(line[i]);
        if (len > 0 && line[i][len-1] == '\n') {
            line[i][len-1] = '\0';
        }
        // 逐行更新CRC值
        crc = crc32(crc, (const Bytef*)line[i], strlen(line[i]));
        i++;
    }
    fclose(fptr);

    int tot = i;
    printf("\nThe content of the file %s are: \n",filename);
    for(j = 0; j < tot; ++j)
        printf(" %s\n", line[j]); // 修正下标为循环变量j

    printf("%s's crc32 in hex: %lX\n", filename, crc);
    return 0;
}

编译运行注意事项

编译时需要链接zlib库,命令如下:
gcc 你的代码文件名.c -o crc_calc -lz
运行前请确保input.txt存放在程序执行的当前工作目录下。

内容的提问来源于stack exchange,提问作者mufak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:06:04