Reputation: 26434
When writing a simple program for a POSIX-compliant OS which accepts input and produces output, when and why should
myprogram file.in
be preffered over
myprogram < file.in
and vice versa?
I like the latter because I feel that file handling should be the responsibility of the shell, not my program. On the other hand, I'm not so sure how the same code could work for both files and stdin—shouldn't stdin be interactive, i.e. prompt you for your input? Whereas in a file, the format is understood and predefined, e.g. there is a single integer which is the input value (in which case another option would be to simply accept the value as a command line argument), or each line contains a test case which is a list of space-separated numbers, etc.
Examples would be great.
Note that I've already seen Shell redirection vs explicit file handling code and none of the answers really answered this question in a general sense.
Upvotes: 1
Views: 143
Reputation: 14830
Most POSIX utilities will act on a file if one is given at the command line, or on stdin/stdout if no file(s) specified. Common styles are
myprogram filename
myprogram -f filename
myprogram --file=filename
Or individual input and output specifiable.
This allows the flexibility of supplying a file, or using redirection or pipelining.
main
handles parameters and opening a file if necessary, then passes off the open file stream -- whether it's from stdin
or the file you opened -- to your processing function.
This fits in with the UNIX philosophy, as sgmorrison mentioned.
Upvotes: 1
Reputation: 986
This is down to preference, and the intended use of your program should inform your decision.
The UNIX philosophy suggests writing simple tools connected by clean interfaces. Creating a tool that accepts stdin will make it more versatile. You will be able to feed the tool from existing files, or from the output of any other POSIX command.
Upvotes: 3