I guess I’m having a hard time understanding the differences. This is important because how would the user know what to type at the command line? At the command line, a.out file is for file processing where you need to explicitly open the file. a.out < file is redirected input and you don’t need to open the file. Pros and cons?
I guess I’m having a hard time understanding the differences. This is important because
Share
Stdin is particularly useful when you want to be able to pipe the output of one program to the input of another program, and so on in a chain, like this:
(which will print out the number of lines in myfile.txt containing the string MyKeyword)
If the “grep” and “wc” utilities were set up to only read from a specified file, rather than from stdin, the above task would be more difficult; you’d have to do it in multiple steps instead:
… which would be awkward and also requires writing a temporary file to the disk, which can be problematic (e.g. what if there was already a temp.txt file in the current directory? Oops, you just overwrote it, too bad! Or what if you don’t have write-access to the drive? No way to write out a temporary file then)
On the other hand, sometimes your program needs to read from more than one file. For example, if you wanted to concatenate several files together you can do this:
cat part1.txt part2.txt part3.txt > wholething.txt
If “cat” only supported reading from stdin it would be difficult to do such a thing, as you’d need some way to pipe multiple files into cat’s stdin stream.
Also, if a program needed to read the file in non-linear order (e.g. fseek() forward or back in the file rather than just reading it straight through) it wouldn’t be able to do that using stdin, since you can’t seek on a pipe.