Here simple code I am not getting the expected output.
#include<stdio.h>
int main()
{
char buf[1024];
while(1)
{
fgets(buf,strlen(buf),stdin);
printf("%s",buf);
printf("hello");
}
}
In the above code I am want whatever the string I enter from keyboard to be printed out to me the same and then hello.
As I know fgets() is a blocking function till I input a string from keyboard and press ENTER it will block the program till that time. So when I run it I expect it as follows
$ ./a.out
I input some text here <ENTER>
I input some text here
hello
But actually what I am getting output is infinite loop of “hello” printed on terminal. Why my fgets() not blocking the program? Any idea?
That’s because the
strlenof your buffer is probably zero. You should be usingsizeofinstead, which gives you the size of the array (1024) rather than the length of the string it contains (indeterminate here).It probably is a zero sized string in your particular case (
*buf == '\0') since thefgetscall is not blocking at all. Actually, it could have a length of one as well since the standard states:In actual fact, as a local variable that hasn’t been initialised,
bufcould contain anything so you’re unwise to rely on it (if it doesn’t contain a null terminator at all, you may even find yourself dumping core as thestrlenruns off the end).If you want a tried and true input function, see here. It has buffer overflow protection, prompting, removal of the newline at the end, and clearing of the line remainder in the event it was too long. I’ll duplicate the code below to make this answer more self-contained.