0

Help me with gets and fgets

What's the difference between "fgets(str, sizeof str, stdin);" and "gets(str)" ? I think both have the same function. Thank you already

8th Jun 2021, 9:52 AM
Rishi
Rishi - avatar
6 Answers
+ 4
as u can see, with fgets we can specify the number of bytes we want to write..fgets also stop when it encounters eof but not gets using gets may cause buffer overfow
8th Jun 2021, 10:05 AM
durian
durian - avatar
+ 3
Rishi there will be no problem till the time the input is within limits of buffer ( arr in this case ) The problem occurs when it reads a string greater than size of your buffer. gets() only know from where to start writing in memory ( starting on the buffer ) and doesn't know when to stop, causing(as Lily Mea mentioned ) buffer overflow if huge input is provided. Whereas fgets() does know when to stop ( provided as argument ) and will not write beyond the limit of your buffer, making it much safer alternative.
8th Jun 2021, 10:56 AM
Arsenic
Arsenic - avatar
+ 1
Oh thank you Arsenic I got it now. Thank you too Lily Mea
8th Jun 2021, 11:07 AM
Rishi
Rishi - avatar
+ 1
Martin Taylor oh okay sure. Thank you
9th Jun 2021, 12:35 PM
Rishi
Rishi - avatar
0
Lily Mea yeah but I don't quite understand it. Here, how does sizeof() function work for a string that is entered? And anyway both are going to stop after the end of the sentence that we entered. So what's the difference?
8th Jun 2021, 10:26 AM
Rishi
Rishi - avatar