Why?
-
gets
is completely unsafe. -
scanf
is hard to use and also can be unsafe if used incorrectly. -
fgets
is much better but is less convenient:-
fgets
includes a trailing newline character. If stripping the newline is desired, some care is needed to deal with occasional cases where a newline is not present. - If the line doesn't fit in the buffer, the caller must decide what to do with the partial line read so far and what to do with the remaining portion of the line. Accepting the partial line might have other security implications, and leaving the rest of the line unread leaves the input stream in an inconsistent state.
-
The POSIX getline
function is a good alternative if available.
For systems where getline
isn't available, or for cases where
gets
-like syntax is more desirable, Chuck Falconer's
ggets
can be used instead. ggets
automatically
allocates a buffer to store the input line. Callers are responsible for
calling free
on the allocated line when no longer needed. The
ggets
code is written in standard C, is portable, and is in the
public domain.
(Note that because ggets
always strips a trailing newline
character, clients will not be able to distinguish a final line that
contains a newline from a final line that does not. Some consider this to
be a bug; others consider this to be a feature.)
With his passing,
Chuck Falconer's website is no longer available (although
archive.org
still has a copy), so I'm providing a copy of his ggets
code here.