krise
krise

Reputation: 535

Reading from stdin into a FILE*

I have a functions that expects a FILE* and I usually create that by reading from a file. Now under certain circumstances I want to read from stdin. Is there a way to read a sentence with previously unspecified length from stdin and write it into a FILE* ?

Upvotes: 0

Views: 233

Answers (3)

pmg
pmg

Reputation: 108968

Yes, just use fp and stdin as needed

void copyline(FILE *fp) {
    int ch;
    while ((ch = fgetc(stdin) != EOF) && (ch != '\n')) {
        fputc(ch, fp);
    }
    if (ch != EOF) fputc('\n', fp);
}

Upvotes: 1

Gaurav
Gaurav

Reputation: 1600

You can use getchar() on a line buffered terminal and read it like this:

 int i;
 while((i=getchar())!=EOF)

And then use it to write it into a file.

Upvotes: 0

Stargateur
Stargateur

Reputation: 26697

stdin, stdout and stderr are already of type FILE *. So you can use it like any other FILE * variable.

Upvotes: 4

Related Questions