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
相关产品推荐
相关产品推荐

