Home Segments Index Top Previous Next

558: Sidetrip

The analog to gets for reading a line directly from a file is fgets, an acronym for file get string:

fgets(name of character array, 
      maximum characters to be read + 1, 
      file-pointer name) 

Like gets, the fgets function generally returns a pointer to the first character in the character array, but should the fgets function encounter the end of a file, it returns NULL. Unlike gets, fgets stops when it either reaches the end of a line or has read the maximum number of characters. If fgets does reach the end of a line, fgets copies an end-of-line character into the array, just before the terminating \0, which appears in the character array no matter what.

Thus, you can read the next line of input from a file into the input_buffer array with the following statement:

                     *-- You do not want more characters than 
                     |   input_buffer can hold 
                     v 
fgets(input_buffer, 100, trade_source); 
                           ^ 
                           | 
                           *-- A file pointer, set up by FILE*