Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not getting expected output from fgets() function

Tags:

c

blocking

fgets

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?

like image 484
Surjya Narayana Padhi Avatar asked Apr 24 '26 18:04

Surjya Narayana Padhi


1 Answers

The problem is strlen(buf) is return 0 because buf[0] just happened to be 0 (not guaranteed). You should use sizeof(buf) instead:

fgets(buf,sizeof(buf),stdin);
like image 127
CrazyCasta Avatar answered Apr 26 '26 10:04

CrazyCasta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!