Home >>c programs >fgets C

fgets C

fgets C

The fgets C is basically a function in the C language that is generally used to read a line from the stream that is specified and store it into the string that is pointed to by str.

In order to make it stop either (n-1) characters are to be read, the end-of-file is reached or the newline character is read, depends on whichever comes first.

The declaration of the fgets function in C is extremely easy and is depicted below for your understanding:

Syntax :

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

Here are the parameters of the syntax of the fgets in C described below:

  • str - This is basically the pointer to an array of the characters where the string that has been read is stored.
  • n − This is basically the maximum number of the characters to be read.
  • stream − This is basically the pointer to a FILE object that generally identify the stream form where the characters are read.

Here is an example of the fgets function in C language that will help you in the deeper understanding of the topic:

#include <stdio.h>
int main () 
   FILE *op;
   char str[60];

   /*first need to  open file for reading */
   op = fopen("myfile.txt" , "r");
   if(op == NULL) 
      perror("There is something wrong while opening file");
   if( fgets (str, 60, op)!=NULL ) 
      /*Need to write the content */
Output :
There is something wrong while opening file: No such file or directory

No Sidebar ads