fgets

Reads a line from the specified file, up to one less than the specified maximum number of characters or up to and including the new-line character, whichever comes first. The function stores the string in str.

Format

#include  <stdio.h>

char *fgets  (char *str, int maxchar, FILE
             *file_ptr);
Function Variants This function also has variants named _fgets32 and _fgets64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions.

Arguments

str
A pointer to a character string that is large enough to hold the information fetched from the file.
maxchar
The maximum number of characters to fetch.
file_ptr
A file pointer.

Description

This function terminates the line with a null character (\0). Unlike gets, fgets places the new-line character that terminates the input line into the user buffer if more than maxchar characters have not already been fetched.

When the file pointed to by file_ptr is opened in record mode, fgets treats the end of a record the same as a new-line character, so it reads up to and including a new-line character or to the end of the record.

Return Values
Pointer to str
NULL  Indicates the end-of-file or an error. The contents of str are undefined if a read error occurs. 

Example

    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
    FILE *fp;
    char c_ptr[130];
    
       /* Open a file with some data -"THIS IS A TEST."   */
    
    if ((fp = fopen ("file.dat","r+") ) == NULL)
         perror ("open error"),exit(1);
    
    fgets(c_ptr,130,fp);
    puts(c_ptr);  /* Display what fgets got.  */
    fclose(fp);
    }
    


Previous Page | Next Page | Table of Contents | Index