来自 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.
我认为 fgets
函数在遇到 \0
或 \n
时停止;为什么当 fgets
应该正确处理输入时,此手册页建议空字节是“危险的”?此外,getline
和 fgets
之间有什么区别,fgets
函数是否真正被认为已弃用 < strong>C99 还是 future 的 C 标准?
最佳答案
不,fgets
实际上并未在 C99 或当前标准 C11 中弃用。但是该教程的作者是对的,fgets
在遇到 NUL 时不会停止,并且没有报告读取此类字符的机制。
The
fgets
function reads at most one less than the number of characters specified byn
from the stream pointed to bystream
into the array pointed to bys
. No additional characters are read after a new-line character (which is retained) or after end-of-file.
(§7.21.7.2)
GNU 的 getdelim
和 getline
已在 POSIX 2008 中标准化,因此如果您的目标是 POSIX 平台,那么改用这些平台可能不是一个坏主意。
编辑 我认为在 NUL 字符面前使用 fgets
绝对没有安全的方法,但是 R..(见评论)指出有:
char buf[256];
memset(buf, '\n', sizeof(buf)); // fgets will never write a newline
fgets(buf, sizeof(buf), fp);
现在在 buf
中查找最后一个非 \n
字符。不过,我实际上并不推荐这种组合。
关于c - 为什么不推荐使用 fgets 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323185/