UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

8.4.  Input functions to read strings in a secure way

As we have seen in the last section, when using functions gets and scanf to read in a sequence of characters, your program will eventually fail, because these functions do not control if the user types more characters than the maximum size of the array that has to hold them. To avoid this, C has two more functions which make the user input reading safer: fgets and getline.

8.4.1.  The fgets function

The syntax of the fgets function is the following:

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

Here s references a character array that is used to store characters read from the opened file pointed to by stream. n specifies the maximum number of array elements. The function reads a sequence of up to n-1 characters from the file referenced by stream, and writes it to the buffer indicated by s, appending the string terminator character '\0'. If a newline character('\n') is read, it also stops and the string written to the buffer is terminated after the newline character (so this character is also included). The function returns the pointer to the string buffer if anything was written to it, or a null pointer if an error occurred or if the file position indicator was at the end of the file. If you have entered more characters than what the function has the capacity to read, you will have to clear the buffer in order not to get those remain characters in the next fgets call.

fgets is safer than gets, but this function involved a little more work basically because of two issues. One is that, if you have entered more characters than what the function has the capacity to read, you will have to clear the buffer in order not to get those remain characters in the next fgets call. The second issue is that you have to get rid of the newline character which fgets stores in the array.