Im new to C. I have a problem in understanding a piece of code.
What I don’t understand are two things. The second argument of fgets is the maximum length of bytes can be stored in the buffer.
Why if I type more letters in the terminal and hit enter still the string is printed back in full. I am assuming that if the length of the string inserted in the console is larger than the buffer will overflow and the printf will work because it stops on the termination of the string, but then what it is the point of setting a max limit as second argument to fgets?
#define buff_size 4
//3.71
void good_echo(){
char buf[buff_size];
while(1) {
char* p = fgets(buf, 8, stdin);
if(p == NULL) {
break;
}
printf("%s", p);
}
return;
}
>Solution :
Why if I type more letters in the stdin still the string is printed back. I am assuming that if the length of the string inserted in the console is larger than the buffer will overflow and the printf will work because it stops on the termination of the string,
You get the full input echoed back by the program because the fgets() and printf() calls are inside a loop. Each fgets() call will read and store as many characters as will fit in the buffer, up to and including a newline if one is in fact encountered before the available buffer space is exhausted. If there is more data than will fit in the buffer — because you typed more characters than can fit at once, or because you typed ahead multiple lines at hyperspeed — then whatever is not read by fgets() remains in the stream, waiting to be read via some future call to an I/O function.
In your program, the printf() echoes back the characters that were read and stored, and control then loops back to fgets(). If there are more characters available to read, then it will read them, up to, again, the buffer capacity or a newline, whichever comes first. In this way, one long line may be consumed from the standard input and echoed to the standard output over multiple iterations of the loop.
but then what it is the point of setting a max limit as second argument to fgets?
It does exactly what it is advertized to do. On any call, fgets() will write up to that many bytes into the provided buffer.