我试图写一个猫克隆锻炼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
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;
}
}