Usually, you'd only use redirections for standard input (fd 0, with the <
redirection operator), standard output (fd 1, >
) and standard error (fd 2, 2>
), which seems to limit you to only one input stream.
(Of course you could do something like cat f1 f2 f3 | program
, but telling the files apart would be hard.)
But, if you actually really want to, you can use other file descriptor numbers for inputs too. This is done in the same way as when redirecting stderr
, just add the number before the redirection operator. So, running
./prog 3<file1 4<file2 5< file3
would open the given files in fd's 3, 4 and 5 and pass those on to ./prog
. The program can then use fdopen
to associate stdio streams (FILE *
) with them. The biggest issue here is that you'll need some way of knowing which fd's to use in the program, and that would quickly require using something like command line arguments. The toy example below is fixed to use those three fd's, which of course does not scale in the least.
Instead, you'd be better off doing what all other programs do, and passing the file names as command line arguments. Even in the situations where you need to refer to an already-open file descriptor, many Unixes have a way of referring to them by name: /dev/fd/1
etc. (Process substitution, which is something like a generalized pipe, is one of those things that need to do this.)
Silly fdopen()
example:
#include <stdio.h>
void read_a_line(int fd)
{
char buf[64];
FILE *f = fdopen(fd, "r");
fgets(buf, 64, f);
printf("fd %d: %s\n", fd, buf);
fclose(f);
}
int main(void)
{
read_a_line(3);
read_a_line(4);
read_a_line(5);
return 0;
}