Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing stdin to a file

Tags:

c

stream

stdin

pipe

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.

like image 274
WhyNotHugo Avatar asked Sep 06 '25 03:09

WhyNotHugo


1 Answers

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.

like image 199
Ernest Friedman-Hill Avatar answered Sep 07 '25 21:09

Ernest Friedman-Hill