fgets

get a string of characters from a file

Synopsis:

#include <stdio.h>
char *fgets( char *buf, size_t n, FILE *fp );

Description:

The fgets() function gets a string of characters from the file designated by fp, and stores them in the array pointed to by buf. The fgets() function stops reading characters when:

whichever comes first. The new-line character is not discarded. A null character is placed immediately after the last character read into the array.

A common programming error is to assume the presence of a new-line character in every string that is read into the array. A new-line character will not be present when more than n-1 characters occur before the new-line. Also, a new-line character might not appear as the last character in a file, just before end-of-file.

The gets() function is similar to fgets(), except that it operates with stdin, it has no size argument, and it replaces a newline character with the null character.

Returns:

See also:

errno, fopen(), getc(), gets(), fgetc()

Examples:

#include <stdio.h>

void main()
  {
    FILE *fp;
    char buffer[80];

    fp = fopen( "file", "r" );
    if( fp != NULL ) {
      while( fgets( buffer, 80, fp ) != NULL )
        fputs( buffer, stdout );
      fclose( fp );
    }
  }

Classification:

ANSI

Systems:

All (except DOS/PM)