Name

fgets

Synopsis

Reads a string from a file

#include <stdio.h>
char *fgets( char * restrict buffer, int n, FILE * restrict fp );

The fgets() function reads a sequence of up to n − 1 characters from the file referenced by the FILE pointer argument, and writes it to the buffer indicated by the char pointer argument, appending the string terminator character '\0'. If a newline character ('\n') is read, reading stops and the string written to the buffer is terminated after the newline character.

The fgets() function returns the pointer to the string buffer if anything was written to it, or a null pointer if an error occurred or if the file position indicator was at the end of the file.

Example

FILE *titlefile;
char title[256];
int counter = 0;

if ((titlefile = fopen("titles.txt", "r")) == NULL)
  perror( "Opening title file" );
else
{
  while (fgets( title, 256, titlefile ) != NULL )
  {
    title[ strlen(title) -1 ] = '\0';       // Trim off newline character.
    printf( "%3d: \"%s\"\n", ++counter, title );
  }
  /* fgets() returned NULL: either EOF or an error occurred. */
  if ( feof(titlefile) )
    printf("Total: %d titles.\n", counter);
}

If the working directory contains an appropriate text file, the program produces output like this:

  1: "The Amazing Maurice"
  2: "La condition humaine"
  3: "Die Eroberung der Maschinen"
Total: 3 titles.

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.