Science, asked by abhineshpatel6533, 1 year ago

What is the difference between gets and fgets and between puts and fputs in C?

Answers

Answered by ramtanu51
1
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;
Similar questions