Hey guys,
I'm writing a rudimentary program to explore the behavior of the stdin buffer and I've encountered something that I cannot make much sense of. The code simply takes input from the shell level and thus stores it in stdin, then the reads the input one char at a time, stores it into an array, and prints of the contents of that array to stdout. The way the getline function is designed to operate is to read chars from the stdin until a newline char, '\n', an EOF signal is reached, or until the for-loop counter value exceeds BUFF_SIZE - 2 (8). Once these are read, it then appends the newline char and the NULL byte char, '\0', to the array and returns 1 to the main function (I terminate the program manually using CTRL + C keystroke combination).
Code:
1 #include <stdio.h>
2
3 #define BUFF_SIZE 10
4
5 int getLine(char buff[]);
6
7 main()
8 {
9 char line[BUFF_SIZE];
10
11 while(getLine(line) != 0)
12 printf("%s", line);
13
14 return 0;
15 }
16
17 int getLine(char read[])
18 {
19 int i, c;
20
21 for(i = 0; i < BUFF_SIZE - 2; ++i) {
22 c = getchar();
23 if(c == EOF || c == '\n')
24 break;
25 read[i] = c;
26 }
27 read[i++] = '\n';
28 read[i] = '\0';
29
30 return 1;
31 }
Now for the problem...For when I enter the char sequence: 0123456789 and press Enter the output reflects exactly how I expected it to. However, when I enter the char sequence: 0123456789 and send the EOF signal (CTLR + d) the program behaves somewhat unexpectedly. It will successfully print the first "01234567" string of chars, but then the remaining "89EOF" is not printed until I send press Enter. If you look at the source code, this is not how the program should execute so I am wondering what exactly is happening. It should replace the EOF with a newline char and append the NULL byte char and proceed to print this string, but it's almost as if it's waiting for me to prompt it, by pressing the Enter key, to do so. Can anyone help me figure this out?