I have encountered a problem while programming in Linux using C, and I have narrowed it down to the following question.
#define BUF_SIZE 10
int main()
{
int cnt;
char buf[BUF_SIZE];
cnt = read(STDIN_FILENO, buf, BUF_SIZE);
printf("cnt = %d\n", cnt);
return 0;
}
Given the code above, if I use the terminal as input, and put in 3 characters and then hit enter, then I got "cnt = 4".
./a.out
abc
cnt = 4
But if I use redirection, and use a file, which contains two lines, as the input, read()
does not stop at the newline character, but proceed and read the whole file. Like this
//inside input_file. This line is not in the file.
123
456
Then I got
./a.out < input_file
cnt = 8
Now here is my question. Why read()
does not stop after reading the first line in the file ? What is the difference between a terminal input and a file input ?
Some references to explain this would be appreciated.