gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:37:57 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com