getsis completely unsafe.
scanfis hard to use and also can be unsafe if used incorrectly.
fgetsis much better but is less convenient:
fgetsincludes 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.
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.
allocates a buffer to store the input line. The
ggets code is
written in standard C, is portable, 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.)
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.