c - stdin 在第一行之后到达 EOF

标签 c std stdin fgets eof

我正在尝试使用 type file.txt | 通过管道将文件传输到我的程序myprogram.exe。我正在阅读它:

char *line;
struct block *newblock, *cur;
int i, osl, cbs, rs;
int startblock;

/* read in the blocks ... */
while (!feof(stdin) && !ferror(stdin)) {
    cbs = 2048;
    line = (char *)malloc(cbs + 1);
    if (!line) {
        perror("malloc");
        exit(1);
    }
    line[cbs] = '\0';

    /* read in the line */
    if (!fgets(line, cbs, stdin)) {
        free(line);
        continue;
    } else {
        while (line[cbs - 2]) {
            /* expand the line */
            line = (char *)realloc(line, (cbs * 2) + 1);
            if (!line) {
                perror("realloc");
                exit(1);
            }
            line[cbs * 2] = '\0';

            /* read more */
            if (!fgets(line + cbs - 1, cbs + 1, stdin))
                break;

            cbs *= 2;
        }
    }
    ...
}

但在读取第一行后,feof() 返回 true,即使文件中有多行。怎么会这样呢?

最佳答案

代码有多个问题:

  • 文件结尾测试不正确:feof() 仅在读取函数失败后提供有意义的信息。
  • 重新分配方案已损坏:您测试数组的倒数第二个字节,但如果行较短,fgets() 可能未设置此字节。

以下是修复程序的方法:

  • 如果您的系统支持,请使用getline()getline() 分配足够大的缓冲区以一次读取整行。
  • 或使用fgets读取行片段并检查它是否以换行符结尾。

关于c - stdin 在第一行之后到达 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56940826/

相关文章:

c++ - 数组不是命名空间::std 的成员

python - 在 os.dup2() 之后重定向标准输出/输入/错误

c - 这段代码是哪种排序技术?

c++ - 如何为 const 模板参数定义复制构造函数?

c++ - 在 C++ 中的重载运算符中使用局部变量

c - 如何在 C 中检查 stdin == stdout

bash - 此 shell 语法的机制 : ${1:-$(</dev/stdin)}

c - C中.h和.c文件之间的关系

c - dll 的结构参数被损坏

c - 城市名称排序失败