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

fgets()不完整行检测逻辑存在误判,如何修正?

修正fgets()不完整行检测逻辑的问题

原代码试图检测fgets()读取的行是否过长,但存在边界场景判断错误:当输入内容长度刚好等于缓冲区最大可读取字符数且无尾随换行时,错误判定为行过长。

原代码

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

int main(){
  char line[5];
  while(fgets(line, 5, stdin)){
    int length = strlen(line);
    if (length == 4 && line[3] != '\n') {
      puts("line too long");
      return 1;
    }
  }
  puts("correct file");
  return 0;
}

原代码测试情况

正常工作场景

$ cc test.c -o test
$ printf '012\n' | ./test
correct file
$ printf '012' | ./test
correct file
$ printf '0123\n' | ./test
line too long

失效场景

当输入内容长度等于缓冲区最大可读取字符数(4个字符)且无换行时,错误判定为行过长:

$ printf '0123' | ./test
line too long

问题根源

原逻辑仅判断了「缓冲区满且无换行」,但未区分两种情况:

  • 输入流还有剩余字符未读取(真正的行过长)
  • 输入流已到末尾,这是最后一行(合法场景)

修正方案

当检测到缓冲区满且无换行时,需要额外检查输入流是否还有后续字符。如果能读到非EOF的字符,说明行过长;如果读到EOF,说明是合法的末尾行。

修正后的代码:

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

int main(){
  char line[5];
  int c;
  while(fgets(line, 5, stdin)){
    int length = strlen(line);
    if (length == 4 && line[3] != '\n') {
      // 检查输入流是否还有剩余字符
      c = getchar();
      if (c != EOF) {
        puts("line too long");
        // 若有剩余字符,无需继续读取,直接退出
        return 1;
      }
      // 读到EOF,说明是最后一行,无需报错
    }
  }
  puts("correct file");
  return 0;
}

修正后测试验证

# 合法场景:刚好填满缓冲区且无换行,输入到末尾
$ printf '0123' | ./test
correct file

# 真正行过长场景:超过缓冲区容量
$ printf '01234' | ./test
line too long

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:01:09