Larry
Larry

Reputation:

passing input from standard input to a file (C programming)

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

Answers (3)

Chris Lutz
Chris Lutz

Reputation: 75389

I can see a couple of options:

  1. Rewrite your function to take text, and require that people who call it read from the file and pass the read text to your function, rather than passing a file to read. You can also write a wrapper function that takes a file, reads the contents, and passes the contents to your function that takes text, so that people can continue to simply pass filehandles to your function.
  2. Learn how your compiler implements filehandles, and make a function that creates a filehandle mapped to a string, where "reads" from the filehandle get the next character in the string. This may be highly compiler-dependent, and may be tricky, and may be more trouble than it's worth. Depends on how badly you need it.
  3. If you can get away with it, 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

Jonathan Leffler
Jonathan Leffler

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

Martin Beckett
Martin Beckett

Reputation: 96109

You can use the freopen() function to open stdin.

See also Rerouting stdin and stdout from C

Upvotes: 0

Related Questions