My program needs to accept three kinds of input commands below:
./Myprogram input.txt
./Myprogram < input.txt
./Myprogram
I’m thinking about using argc to check the number of arguments to resolve the first two situations (since redirection doesn’t count as an argument). But then I stuck on the last case, which simply waits for an user input.
I’m wondering if there is a way to tell if a redirection is present in the shell command?
For a more complicated scenario such as a mix of redirection and argv forms (see below). Is there a way to do it or it’s simply a bad design for taking user commands?
./Myprogram input1.txt input2.txt input3.txt
./Myprogram input1.txt < input2.txt input3.txt
./Myprogram
Any help will be much appreciated!
Z.Zen
Redirection will never be seen by your program as an argument. So in:
the second and third forms are identical. As for your second set of possibilities:
the second line is equivalent to:
and it’s also indistinguishable from:
(the only different being where standard input actually comes from).
A typical way some programs handle mixed input from stdin and files specified on the command line is to accept
"-"as a special filename meaning “use stdin as the input file at this position in the argument list”. Many such programs will default to processing a singleton-list of"-"if the argument list is empty.