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

C语言如何获取文件内最长行的长度

问题根因
  • 核心内存访问错误原因:char *input = NULL 未分配任何可写入的内存空间,fscanf 尝试将读取到的行内容写入空指针指向的地址,直接触发非法内存访问。
  • 编译级笔误:定义的行长度变量名为longestLinelength,长度判断时误写为longestLineLength(末尾L大小写不一致),代码无法正常编译通过。
  • 缺少文件打开校验:fopen 调用后未判断返回值,如果目标文件不存在、无读取权限会返回NULL,后续所有文件操作都会触发崩溃。
  • 格式符逻辑缺陷:%[^\n] 仅会读取换行符之前的内容,不会消耗文件流中的换行符,下一次fscanf调用会直接匹配失败,进入死循环。
  • 系统调用参数错误:fclose 缺少要关闭的文件指针参数,正确写法为fclose(inputData)。
正确实现方案

推荐使用逐字符统计的方案,不需要提前申请缓冲区,完全规避内存溢出风险,适配任意长度的行:

#include <stdio.h>
#include <stdlib.h>

int get_max_line_length(const char *file_path) {
    FILE *inputData = fopen(file_path, "r");
    if (inputData == NULL) {
        perror("文件打开失败");
        return -1;
    }

    int longestLineLength = 0;
    int currentLineLength = 0;
    int ch;

    // 逐字符读取统计
    while ((ch = fgetc(inputData)) != EOF) {
        if (ch == '\n') {
            // 遇到换行符更新最长行长度
            if (currentLineLength > longestLineLength) {
                longestLineLength = currentLineLength;
            }
            currentLineLength = 0;
        } else {
            currentLineLength++;
        }
    }

    // 处理最后一行没有换行符的情况
    if (currentLineLength > longestLineLength) {
        longestLineLength = currentLineLength;
    }

    fclose(inputData);
    return longestLineLength;
}

int main() {
    int max_len = get_max_line_length("input.txt");
    if (max_len >= 0) {
        printf("最长行长度为: %d\n", max_len);
        // 后续可以用 max_len + 1 申请空间(预留字符串结束符\0的位置)
        char *buf = calloc(max_len + 1, sizeof(char));
        // 后续读取逻辑...
        free(buf);
    }
    return 0;
}

注意:申请内存时需要给最长行长度+1,预留字符串结束符\0的存储位置,避免字符串操作时越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:27:02