Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from stdin write to stdout in C

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

}
like image 438
yasar Avatar asked Apr 12 '12 17:04

yasar


People also ask

How do you read from stdin in C?

The built-in function in c programming is getline() which is used for reading the lines from the stdin. But we can also use other functions like getchar() and scanf() for reading the lines.

What is stdin and stdout in C?

In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr).

Can you write to stdin C?

In the case you have, stdin is used to read FROM THE CONSOLE, not write to it! If you want to do that, then use stdout.

What is stdin in C language?

Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java.


1 Answers

i can quote an answer by me: https://stackoverflow.com/a/296018/27800

fread(buffer, sizeof(char), block_size, stdin);
like image 152
Peter Miehle Avatar answered Oct 26 '22 04:10

Peter Miehle