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.
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.