What is fgets() in C?

fgets() is a standard C library function that is used to read a string of characters from a file at the location indicated by the file pointer. Below is the declaration of the fgets() function:

char *fgets (char * str,int size, FILE * stream);

Return value

if the read operation from the file is successful, the fgets() function return the string that is read. EOFEnd-of-File is returned if there is an error when reading from the file.

Parameters of the fgets() function

  • str: Pointer to the character array to store the string read from the file.
  • size: Maximum number of characters that can be read from the file.
  • stream: Pointer to the file from which the character is to be read.

Example

Consider the code snippet below, which uses fgets() to read the content of a file:

main.c
fgetsExample.txt
#include <stdio.h>
int main() {
FILE * fPointer;
char str[100];
fPointer = fopen ("fgetsExample.txt", "r");//opening file
while( !feof(fPointer) )//checking EOF
{
fgets(str, 100, fPointer);
if(str!=NULL)//if EOF returned
{
printf("%s",str);
}
}
fclose(fPointer);
return 0;
}

The fgets() function is used in line 12, which reads and subsequently prints the content of the file fgetsExample.txt on the screen.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved