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;
}
}
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.
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).
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.
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.
i can quote an answer by me: https://stackoverflow.com/a/296018/27800
fread(buffer, sizeof(char), block_size, stdin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With