[Previous]
[Contents]
[Next]

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 newline character isn't discarded. A null character is placed immediately after the last character read into the array.


Note: A common programming error is to assume the presence of a newline character in every string that is read into the array. A newline character will not be present when more than n-1 characters occur before the newline. Also, a newline 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.


Note: It's better to use fgets() than gets(). With gets(), data beyond the array buf is destroyed if a newline character isn't read from the input stream stdin before the end of the array buf is reached.

Returns:

The buf argument, or NULL if end-of-file is encountered, or a read error occurs. When an error has occurred, errno indicates the type of error detected.

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

Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fgetc(), fgetchar(), fopen(), getc(), getchar(), gets(), ungetc()


[Previous]
[Contents]
[Next]