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

C语言读取多类型多行数据时的EOF问题及解决方案咨询

问题:处理无换行符的文件最后一行读取异常

我在复现一个C语言读取多行不同类型数据的实现时,使用了如下shortread函数来验证行读取完整性并去除换行符:

/** validate complete line read, remove tailing newline from 's'.
 *  returns 1 on shortread, 0 - valid read, -1 invalid/empty string.
 *  if shortread, read/discard remainder of long line.
 */

int shortread (char *s, FILE *fp)
{
    if (!s || !*s) return -1;
    for (; *s && *s != '\n'; s++) {}
    if (*s != '\n') {
        int c;
        while ((c = fgetc (fp)) != '\n' && c != EOF) {}
        return 1;
    }
    *s = 0;
    return 0;
}

当文本文件最后一行没有换行符(内容为4 27 \0)时,执行以下读取代码:

if (!fgets (buf, MAX_MINSEC, fp)) break;
b = shortread (buf, fp);

由于buf中最后一个字符是\0而非\n,shortread会返回1,导致最后一行无法打印,当前仅输出:

3:40  First Artist I Like               First Title I Like

添加空行可以解决这个问题,但我想找其他方法,让两行都能正常打印出如下内容:

3:40  First Artist I Like               First Title I Like
4:27  Fifth Artist is Good              Fifth Title is Good

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:10:40