我想写一个猫克隆锻炼C,我有这样的代码:到stdout用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);'。 – 2012-04-12 18:14:50
这里fread()几乎总是导致零字节,除非你输入正好512个字符。 – 2012-04-12 18:17:56
@JohnBode我的编辑看起来如何? – yasar 2012-04-12 18:32:15