What are fgets() and gets() in C?

The fgets() and gets() methods in the C language read string values with spaces.

fgets()

fgets() reads the data from the given stream until the new line character is read, (val-1) characters are read, or the end of the file is reached. This then stores this data into the string.

Parameter

  • str: It is the pointer to an array of characters that will store the string that is read.
  • val: It is the count of the characters to be read.
  • stream: It is a pointer that points to a file object.

Return type

  • char*: It is the character array.

Syntax

char *fgets(char *str, int val, FILE *stream)

Example

In this example, if we input “Educative for learning,” the output will only be “Educative.” This is because the fgets() function has a LIMIT of reading only 10 characters. So, it will only read LIMIT-1, or 9, characters from the input string.

#include <stdio.h>
#define LIMIT 10
int main()
{
char str[LIMIT];
fgets(str, LIMIT, stdin);
printf("str is: %s\n", str);
return 0;
}

Enter the input below

Explanation

  • Lines 1 to 5: We declare a limit to read the number of characters, and a character array with the size of the limit.
  • Line 6: We call the fgets() function to read the number of characters defined by the limit and store them into str.
  • Line 7: We print the str.

gets()

gets() reads the data from the given stream until the new line character is read, or the end of the file is reached. This then stores this data into the string.

Parameter

  • str: It is the pointer to an array of characters that will store the string that is read.

Return Type

  • char*: It is the character array.

In this case, defining a size of str will be of no use. This is because the function reads till the new line character is reached. Moreover, size is not a parameter in this function, unlike in fgets().

Syntax

char * gets ( char * str );

Example

In this example, if we input “Educative for learning,” the entire string will be stored into str. This is because the function gets() function will read the string until the new line character, irrespective of its size.

#include <stdio.h>
#define LIMIT 15
int main()
{
char str[LIMIT];
gets(str);
printf("str is: %s\n", str);
return 0;
}

Enter the input below

Explanation

  • Lines 1 to 5: We declare the limit to read the number of characters and a character array having the size of the limit.
  • Line 6: We call the gets() function to read the number of characters until the new line character, irrespective of limit, and store them into str.
  • Line 7: We print the str.

Note: In this case, an error might appear. This is because the gets() function is not ideal to use when no array limit is checked, and it keeps on reading until the new line character.