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. Callers are responsible for
free on the allocated line when no longer needed. The
ggets code is written in standard C, is portable, and is in the
(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.)