fgets

Defined in header <stdio.h>
char *fgets( char          *str, int count, FILE          *stream );
(until C99)
char *fgets( char *restrict str, int count, FILE *restrict stream );
(since C99)

Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always null-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

Parameters

str - string to read the characters to
count - the length of str
stream - file stream to read the data from

Return value

str on success, NULL on failure.

If the failure has been caused by end-of-file condition, additionally sets the eof indicator (see feof()) on stream. If the failure has been caused by some other error, sets the error indicator (see ferror()) on stream.

Example

fgets with error checking.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    FILE* tmpf = tmpfile();
    fputs("Alan Turing\n", tmpf);
    fputs("John von Neumann\n", tmpf);
    fputs("Alonzo Church\n", tmpf);
 
    rewind(tmpf);
 
    char buf[8];
    while (fgets(buf, sizeof buf, tmpf) != NULL)
          printf("\"%s\"\n", buf);
 
    /* Test reason for reaching NULL. */
    if (feof(tmpf))          /* if failure caused by end-of-file condition */
       puts("End of file reached");
    else if (ferror(tmpf))   /* if failure caused by some other error      */
         {
            perror("fgets()");
            fprintf(stderr,"fgets() failed in file %s at line # %d\n", __FILE__,__LINE__-9);
            exit(EXIT_FAILURE);
         }
 
    return EXIT_SUCCESS;
}

Output:

"Alan Tu"
"ring
"
"John vo"
"n Neuma"
"nn
"
"Alonzo "
"Church
"
End of file reached

References

  • C11 standard (ISO/IEC 9899:2011):
    • 7.21.7.2 The fgets function (p: 331)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.19.7.2 The fgets function (p: 296)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.9.7.2 The fgets function

See also

reads formatted input from stdin, a file stream or a buffer
(function)
(until C11)(since C11)
reads a character string from stdin
(function)
writes a character string to a file stream
(function)
C++ documentation for fgets
doc_C_Language
2016-10-10 18:35:13
Comments
Leave a Comment

Please login to continue.