Solution for how does this C code with input through < work? (K&R) is Given Below:
$ ./main < input
If I were to check for new lines in python, I would open the file and then analyze the lines, but this almost seems like magic.
int main(){
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == 'n')
nl++;
printf("%dn", nl);
return 0;
}
How does it know to accept any input file without being stated within the code?
The <
symbol in the shell is an input redirection. It states that the contents of the given file input
in this case, will be read as stdin.
So any function such as getchar
that reads from stdin will actually be reading from the file input
in this case.
A similar program in Python would also use functions that read from stdin instead of from a file.