yas*_*sar 4 c io stdin stdout stdio
我正在尝试编写一个猫克隆来练习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;
}
Run Code Online (Sandbox Code Playgroud)
我试过了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;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以引用一个答案:https://stackoverflow.com/a/296018/27800
fread(buffer, sizeof(char), block_size, stdin);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36942 次 |
最近记录: |