Previous Page
Next Page

gets

Reads a line of text from standard input

#include <stdio.h>
char *gets ( char *buffer  );

The gets( ) function reads characters from the standard input stream until it reads a newline character or reaches the end of the stream. The characters read are stored as a string in the buffer addressed by the pointer argument. A string terminator character '\0' is appended after the last character read (not counting the newline character, which is discarded).

If successful, the function returns the value of its argument. If an error occurs, or if the end of the file is reached before any characters can be read in, gets( ) returns a null pointer.

The gets( ) function provides no way to limit the input length, and if the stdin stream happens to deliver a long input line, gets( ) will attempt to store characters past the end of the of the available buffer. Such buffer overflows are a potential security risk. Use fgets( ) instead, which has a parameter to control the maximum input length.


Example

char buffer[1024];
char *ptr = buffer;

/* 7/11/04: Replaced gets( ) with fgets( ) to avoid potential buffer overflow
 * OLD:  while ( gets( buffer ) != NULL )
 * NEW: below
 */
while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
{
  /* ... process the line; remember that fgets( ), unlike gets( ),
     retains the newline character at the end of the string ... */
}

See Also

The function fgets( ); the corresponding string output functions, puts( ) and fputs( ); the C99 functions for wide-character string input, getws( ) and fgetws( )


Previous Page
Next Page