#include <stdio.h> char *gets(char *str);
gets
reads a line of data from the stream stdin
and stores the
data in the area addressed by str
. The gets
function terminates the input line
with a null character.
Note:
Although many of the code examples in this book use gets
, this
function should not be used in production code. gets
was used
to keep the SAS/C examples as simple as possible.
gets
returns str
. If no characters are read due to end of file
or if an error occurs during the read, 0 is returned.
gets(str)
is approximately equivalent to the following, except that the
new-line character that terminates the input line is not stored:
fgets(str, INFINITY, stdin)Because there is no upper bound to the number of characters read,
gets
may store into memory beyond the bounds of str
. Therefore, for safety,
other functions should be considered instead of gets
.
#include <stdio.h> #define MAXLINE 80 #define SAFETY 40 main() { char line[MAXLINE + SAFETY]; for (;;){ /* Instruct user to type up to MAXLINE characters. To */ /* end the program, enter EOF at the input prompt. */ printf("Enter a line of data (to %d characters)n",MAXLINE); /* Read data into str from stdin. */ if (gets(line)){ /* Write string to stdout; check for error. */ if (puts(line) == EOF) break; } else break; } }
fgets
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.