You can, but it's not a good idea. Normally programs start with three file descriptors open:
- 0 is standard input, where commands that process text in some way read input if it's not coming from a file.
- 1 is standard output, for normal data produced by a command if the data isn't explicitly going to a file.
- 2 is standard error, for diagnostic messages that aren't part of the useful data produced by the command.
You can violate these conventions and use more file descriptors, but that means your application will only be directly usable in an environment where the caller has specified the right file descriptors. You won't easily be able to test for that in your application: since file descriptors 3 and above aren't regulated, they may be closed when your application starts (this can be detected), or they may be open for some unrelated purpose (this cannot be detected).
Passing file names on the command line is the normal way of specifying multiple input or output files.
That being said, to access arbitrary file descriptors:
In the shell: redirect to the desired number, e.g.
IFS= read -r line <&3
printf "%s\n" "$line" >&4
- In C, call
write with whatever fd you want, or call
fdopen to get an stdio stream.
In Perl, specify a shell redirection as the file name to open to duplicate a file descriptor, or add
= to do a plain
open IN3, "<&=3";
open OUT4, ">&=4";
- In Python, call