### fgets -- Read a String

Format

>     #include <stdio.h>
>     char *fgets (char *string, int n, FILE *stream);

Language Level: ANSI, POSIX, XPG4
fgets reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first. fgets stores the result in string and adds a null character (\0) to the end of the string. The string includes the new-line character, if read. If n is equal to 1, the string is empty.

Return Value
fgets returns a pointer to the string buffer if successful. A NULL return value indicates an error or an end-of-file condition. Use feof or ferror to determine whether the NULL value indicates an error or the end of the file. In either case, the value of the string is unchanged.

Example
This example gets a line of input from a data stream. The example reads no more than MAX_LEN - 1 characters, or up to a new-line character, from the stream.

    #include <stdio.h>

    #if (1 == __TOS_OS2__)
      #define FILENAME "myfile.dat"    /* OS/2 file name */
    #else
      #define  FILENAME "myfile.dat"  /*Windows file name*/
    #endif

    #define  MAX_LEN  100

    int main(void)
    {
       FILE *stream;
       char line[MAX_LEN], *result;

       stream = fopen("FILENAME","rb");

       if ((result = fgets(line,MAX_LEN,stream)) != NULL)
           printf("The string is %s\n", result);

       if (fclose(stream))
           perror("fclose error");
       return 0;

       /****************************************************
       If FILENAME contains:  This is my data file.

       The output should be:

       The string is This is my data file.
       ****************************************************/
    }

feof -- Test End-of-File Indicator
ferror -- Test for Read/Write Errors
fputs -- Write String
gets -- Read a Line
puts -- Write a String
<stdio.h>