我正在尝试编写一个猫克隆程序来练习C语言,我有这段代码:
#include <stdio.h>
#define BLOCK_SIZE 512
int main(int argc, const char *argv[])
{
if (argc == 1) { // copy stdin to stdout
char buffer[BLOCK_SIZE];
while(!feof(stdin)) {
size_t bytes = fread(buffer, BLOCK_SIZE, sizeof(char),stdin);
fwrite(buffer, bytes, sizeof(char),stdout);
}
}
else printf("Not implemented.\n");
return 0;
}
我尝试了echo "1..2..3.." | ./cat
和./cat < garbage.txt
,但是在终端上没有看到任何输出。我做错了什么?
编辑: 根据评论和答案,最终我做了如下操作:
void copy_stdin2stdout()
{
char buffer[BLOCK_SIZE];
for(;;) {
size_t bytes = fread(buffer, sizeof(char),BLOCK_SIZE,stdin);
fwrite(buffer, sizeof(char), bytes, stdout);
fflush(stdout);
if (bytes < BLOCK_SIZE)
if (feof(stdin))
break;
}
}
feof
作为循环条件;它只有在尝试读取文件末尾后才会返回 true,因此您的循环可能会执行多一次。相反,应该检查fread
的结果,如果小于 BLOCK_SIZE,则调用feof
检查文件是否已结束。在fwrite
调用之后需要添加fflush(stdout);
。 - John Bodestdout
之前检查返回的字节数。你可以反转测试的意义,例如if (bytes > 0) fwrite(...) else break;
;毕竟,如果你收到了0字节,那么你可能已经到达了EOF。 - John Bode