Writing stdin to a file

c, pipe, stdin, stream

Solution

You've got the two integer arguments to `fread()` reversed. You're telling it to fill the buffer once, or fail. Instead, you want to tell it to read single characters, up to 1024 times. Reverse the two integer arguments, and it'll work as designed.

Problem

I'm trying to write stdin to a file, but for some reason, I keed reading zero bytes. Here's my source: ``` #include <stdio.h> #include <stdlib.h> #define BUF_SIZE 1024 int main(int argc, char* argv[]) { if (feof(stdin)) printf("stdin reached eof\n"); void *content = malloc(BUF_SIZE); FILE *fp = fopen("/tmp/mimail", "w"); if (fp == 0) printf("...something went wrong opening file...\n"); printf("About to write\n"); int read; while ((read = fread(content, BUF_SIZE, 1, stdin))) { printf("Read %d bytes", read); fwrite(content, read, 1, fp); printf("Writing %d\n", read); } if (ferror(stdin)) printf("There was an error reading from stdin"); printf("Done writing\n"); fclose(fp); return 0; } ``` I'm running `cat test.c | ./test` and the output is just ``` About to write Done writing ``` It seems zero bytes are read, even though I'm piping lots of stuff.

Original source

Related problems