且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从标准输入写入读取C到stdout

更新时间:2023-11-17 23:35:34

我可以通过我举一个答案:的http://计算器.COM / A /二万七千八百分之二十九万六千零一十八

  FREAD(缓冲区的sizeof(炭),BLOCK_SIZE,标准输入);

I am trying to write a cat clone to exercise C, I have this code:

#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;
}

I tried echo "1..2..3.." | ./cat and ./cat < garbage.txt but I don't see any output on terminal. What I am doing wrong here?

Edit: According to comments and answers, I ended up doing this:

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;
    }

}

i can quote an answer by me: http://***.com/a/296018/27800

fread(buffer, sizeof(char), block_size, stdin);