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