While going through C programming by Ritchie and kernighan, I came across the following code.
#include<stdio.h>
int main() {
int t;
t = getchar();
while ((t=getchar()) != EOF) {
putchar(t);
}
return 0;
}
I am not able to understand how can a integer type variable c , be used to handle buffered text stream,
delimited by newline or ctrl-D,
When I tried for ,
printf("%d",getchar());
it’s giving me ASCII
value of only first character, but here t
seems to be manipulating the whole buffer
until I press enter,
and when I press ctrl-D
in between line it just copies the previous buffer content.
does it mean ctrl-D
is a delimiter
as well as `EOF’?
Can someone please explain me the logic behind it?
3
Usually, the operating system handles the buffered text stream. It does this for a variety of reasons, mostly for performance, but also to support features like inline editing.
Your program is sleeping until you either press enter or ctrl-D. At that point, the entire line is passed to your programs input stream. Then each getchar call will retrieve only one character from that stream at a time and return it in t. As long as there is input available, getchar will immediately return with the first character of that data.
So the next question is what happens when the string runs out. Assuming you haven’t indicated end of file with ctrl-D, getchar will then block while waiting for user input, and your program again sleeps while the operating system gets back to work.
So, t
isn’t manipulating the whole line, the operating system is, and t
hasn’t yet been assigned at this point, because getchar hasn’t returned yet.
1