Reputation:
I wrote a program in C which has a function that processes files which can be passed to it by a file pointer.
void process_my_file(FILE *fptr, ...) {
/* do work */
}
I would like to read some input from standard input and pass it to my function, without having to write the input to a temporary file. Would it be possible to pass it through the file pointer argument, as if it were a file, without having to write it to disk? Could it be done through some other argument which I could add to the signature?
I'm new to this, and need some suggestions. Thanks in advance!
Upvotes: 2
Views: 4180
Reputation: 75389
I can see a couple of options:
fseek()
backwards on stdin
so that you can reread the text you read, and then pass stdin
to your function. Of course, if you wanted to change the input from stdin
before you passed it, this won't work. Also, you probably can't fseek()
on an interactive filehandle. OS X lets me get away with it if stdin
is redirected from a file, but you probably shouldn't do this even if you can get away with it for now.Upvotes: 0
Reputation: 753665
You can call your function with stdin
as the argument.
my_process_file(stdin, ...);
The only reason to worry about that is you say 'some input', but most functions like that read all of the file and stop on EOF. Anyway, you can call your function, and as long as it behaves as you require, you'll be fine. You probably shouldn't assume that there's any extra information on standard input after it returns.
Note that the function should not rely on operations such as fseek()
that do not work on pipes or terminals because stdin
is often connected to them.
Upvotes: 6
Reputation: 96109
You can use the freopen() function to open stdin.
See also Rerouting stdin and stdout from C
Upvotes: 0