prev

C Function - fgets

next

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

fgets reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer. Normally fgets returns s and on end of file or error a NULL is returned.

Source code

     
     #include <stdio.h>
     #include <stdlib.h>
     
     #define LEN     256
     
     /*
      * This program reads input from standard input and prints it out to the
      *  screen
      */
     int main ( void ) {
       char *str;
     
       /*
        * allocate a string of size LEN
        */
       if ( NULL == ( str = calloc ( LEN, sizeof ( char ) ) ) ) {
         printf ( "Unable to allocate memory.  Exiting...\n" );
         return ( 1 );
       }
     
       /* 
        * Continue reading lines until we get a NULL termination
        */
       while ( fgets ( str, LEN, stdin ) ) {
         printf ( "%s", str );
       }
     
       free ( str );
     
       return ( 0 );
     }