Easy Tutorial
❮ C If Else C Exercise Example92 ❯

C Library Function - fgets()

C Standard Library - <stdio.h>

Description

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end of the file is reached, whichever comes first.

Declaration

Here is the declaration for the fgets() function.

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

Parameters

Return Value

On success, the function returns the same str parameter. If the end-of-file is encountered and 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 use of the fgets() function.

#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 the contents to stdout */
      puts(str);
   }
   fclose(fp);

   return(0);
}

Assuming we have a text file file.txt, its content is as follows. The file will serve as input for the example:

We are in 2014

Let's compile and run the above program, this will produce the following result:

We are in 2014

C Standard Library - <stdio.h>

❮ C If Else C Exercise Example92 ❯