ProAnswers.org

Out of fgets() and gets() which function is safe to use and why?

Out of functions fgets( ) and gets( ), fgets( ) is safer to use. gets( ) receives a string from the

keyboard and it is terminated only when the enter key is hit. There is no limit for the input string. The string can be too long and may lead to buffer overflow.

Example:

gets(s) /* s is the input string */

Whereas fgets( ) reads string with a specified limit, from a file and displays it on screen.The

function fgets( )

takes three arguments.

First argument : address where the string is stored.

Second argument : maximum length of the string.

Third argument : pointer to a FILE.

Example:

fgets(s,20,fp); /* s: address of the string, 20: maximum length of string, fp: pointer to a file */

The second argument limits the length of string to be read. Thereby it avoids overflow of input buffer.

Thus fgets( ) is preferable to gets( ).