Home » C programming language

Difference between gets() and fgets() in C programming language



Learn: Difference between gets() and fgets() in C programming language with examples.

To read a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will learn what is the difference between gets() and fgets() with examples?

gets()

gets() is used to read string from the standard input device until newline character not found, use of gets() may risky because it does not check the array bound.

For example: if you have a character array with 20 characters and input is more than 20 characters, gets() will read all characters and store them into variable. Since, gets() does not check the maximum limit of input characters, so any time compiler may return buffer overflow error.

Consider the example:

Here, maximum number of characters are 20 and the input length is greater than 20, gets() will read and store all characters (that's wrong and may occur buffer overflow anytime).

#include <stdio.h>
#define MAX 20

int main()
{
	char buf[MAX];
	
	printf("Enter a string: ");
	gets(buf);
	printf("string is: %s\n",buf);
	
	return 0;
}

Output

Enter a string: Hi there, how are you?
string is: Hi there, how are you?

fgets()

fgets() is used to read string till newline character or maximum limit of the character array, use of fgets() is safe as it checks the array bound.

fgets() has following parameters: buffer, maximum length, and input device reference.

Consider the example:

Here, maximum number of characters are 20 and the input length is greater than 20, fgets() will read and store only 20 characters.

#include <stdio.h>
#define MAX 20

int main()
{
	char buf[MAX];
	
	printf("Enter a string: ");
	fgets(buf,MAX,stdin);
	printf("string is: %s\n",buf);
	
	return 0;
}

Output

Enter a string: Hi there, how are you?
string is: Hi there, how are y





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.