Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets maximum size read

Tags:

c

string

fgets

Using fgets to input a string, I have doubts related to length of string read.

For example, consider the following program.

char str[50];
int i;
int len;
printf("Enter name:\n");
fgets(str,11,stdin);
len = strlen(str);
printf("len :  %d\n",len);
  1. If I enter 123456789, strlen gives 10.

  2. If I enter 1234567890, strlen given is 10 again ??

I think strlen is considering newline also for string length. Am I correct? (I understand fgets using newline as part of string)

What's wrong with (2) where I enter exactly 10 characters, Here string length should be 11 right? 10 + 1 (for newline) = 11

like image 683
kumar Avatar asked Jun 07 '26 01:06

kumar


1 Answers

fgets reads at most 1 fewer characters than the length argument given, and does retain the newline as part of the input - so long as the newline is part of the first (length - 1) characters.

So in your first case, assuming that 123456789 is followed by a newline, fgets has read 9 characters including the newline, yielding a string length of 10; in your second case, fgets will stop after reading the 10 characters 1234567890, yielding a string length of 10.

like image 50
pb2q Avatar answered Jun 10 '26 03:06

pb2q



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!