fgets function in c – fgets C Library Function

fgets function in c: The function char *fgets(char *str, int num, FILE *stream); reads up to num-1 characters from stream and store them in a character array pointed by str. It stops reading characters from stream when either num-1 characters are read or newline character is read, or EOF is received. A terminating null character(‘\0’) is automatically appended after the last character copied to str.

Function prototype of fgets

char *fgets(char *str, int num, FILE *stream);
  • str : A pointer to an array of characters where the string read from stream is stored.
  • num : This is the maximum number of characters to read from stream.
  • stream : A pointer to a FILE object which identifies a stream from where characters are read from.

Return value of fgets

This function returns the same str on success, or a null pointer in case of an error. If EOF is encountered before reading any character from stream then it returns a null pointer and the contents of str remain unchanged.

C program using fgets function

The following program shows the use of fgets function to read strings form a stream. Let file “textFile.txt” contains “fgets C Standard Library function” string. The content of this file will get printed by the following program.

fgets C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   char string[100];
 
   file = fopen("textFile.txt", "r");
   if(file == NULL) {
       perror("Error : Unable to open a file");
       return(1);
   } else {
       if(fgets(string, 40, file)!=NULL) {
           /* printing string on standard output */
           puts(string);
       }
       fclose(file);
   }
    
   return(0);
}

Output

fgets C Standard Library function