From The GNU C Programming Tutorial:
The
fgets
("file get string") function is similar to the gets function. This function is deprecated -- that means it is obsolete and it is strongly suggested you do not use it -- because it is dangerous. It is dangerous because if the input data contains a null character, you can't tell. Don't usefgets
unless you know the data cannot contain a null. Don't use it to read files edited by the user because, if the user inserts a null character, you should either handle it properly or print a clear error message. Always usegetline
orgetdelim
instead offgets
if you can.
I thought the fgets
function stops when it encounters a \0
or \n
; why does this manual page suggest a null byte is "dangerous" when fgets
should handle the input properly? Furthermore, what is the difference between getline
and fgets
, and is the fgets
function truly considered deprecated in the C99 or future C standards?
fgets()
does not stop on encountering a null byte; it only stops when it runs out of space, when it encounters a newline, or when it reaches EOF. – Underpants