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.
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 filewhile( !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.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved