C Library Functions -fgets()

C Standard Library - <stdio.h>

Description

C Library Functionschar *fgets(char *str, int n, FILE *stream)Reads a line from the specified stream and stores it instrinto the string it points to. When reading(n-1)When n characters have been read, or when a newline is encountered, or when the end of the file is reached, it stops, whichever comes first.

Declaration

The following is the declaration of the fgets() function.

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

Parameter

  • str-- This is a pointer to a character array that stores the string to be read.
  • n-- This is the maximum number of characters to be read (including the final null character). Usually the length of the array passed as str is used.
  • stream-- This is a pointer to a FILE object that identifies the stream from which characters are to be read.

Return Value

If successful, the function returns the same str parameter. If the end of the file is reached or no characters have been read, the contents of str remain unchanged and a null pointer is returned.

If an error occurs, a null pointer is returned.

Example

The following example demonstrates the usage of the fgets() function.

Example

#include <stdio.h>

int main()
{
   FILE *fp;
   char str[60];

   /* Open the file for reading */
   fp = fopen("file.txt" , "r");
   if(fp == NULL) {
      perror("Error opening file");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      /* Write content to standard output stdout */
      puts(str);
   }
   fclose(fp);
   
   return(0);
}

Suppose we have a text filefile.txt, whose content is as follows. The file will serve as input in the example:

We are in 2014

Let us compile and run the above program, which will produce the following result:

We are in 2014

C Standard Library - <stdio.h>

other extensions