C Standard Library

C <stdio.h> - fgets() Function



The C <stdio.h> fgets() function reads at most (num-1) characters from the given stream and stores them as a C string into str. Parsing stops if a newline character is found, in which case str will contain that newline character, or the end-of-file is reached.

A terminating null character is automatically appended after the characters copied to str.

Syntax

char * fgets ( char * str, int num, FILE * stream );

Parameters

str Specify pointer to an array of chars where the string read is copied.
num Specify maximum number of characters to be copied into str.
stream Specify a pointer to a FILE object that specifies an input stream.

Return Value

  • On success, str is returned, On failure, null pointer is returned.
  • If the failure has been caused due to end-of-file condition, additionally sets the end-of-file indicator feof() on stream. If this happens before any characters could be read, in which case a null pointer is returned and the contents of str remains unchanged.
  • If error occurs due to some other reason, additionally sets the error indicator ferror() on stream.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened using fopen() function in read mode. It reads first 15 characters from the file and prints them on screen.

#include <stdio.h>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  char mystring [16];

  //read first 15 characters from the file
  if(fgets(mystring, 16, pFile) != NULL)
    puts(mystring);
  
  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

This is a test 

❮ C <stdio.h> Library

5