c - 为什么不推荐使用 fgets 函数?

标签 c file-io gnu c99 buffer-overflow

来自 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 use fgets 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 use getline or getdelim instead of fgets if you can.

我认为 fgets 函数在遇到 \0\n 时停止;为什么当 fgets 应该正确处理输入时,此手册页建议空字节是“危险的”?此外,getlinefgets 之间有什么区别,fgets 函数是否真正被认为已弃用 < strong>C99 还是 future 的 C 标准?

最佳答案

不,fgets 实际上并未在 C99 或当前标准 C11 中弃用。但是该教程的作者是对的,fgets 在遇到 NUL 时不会停止,并且没有报告读取此类字符的机制。

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file.

(§7.21.7.2)

GNU 的 getdelimgetline 已在 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/

相关文章:

C - Sprintf 的变量参数?

java - 从文件开头跳过字符

php - 如何从函数中的 file_get_contents 或文件运行 php 代码

java - 将输入流读取到缓冲区的最佳方法

c++ - 在 C、C++ 中检测 Windows 或 Linux

c - 创建AVL树时访问冲突异常

c++ - 搜索算法以查找列表中的 k 个最小值

bash - 如何在命令行参数给出的一系列数字上并行使用 gnu

bash - 如何在没有 Readline 支持的情况下在 bash 实例中设置不区分大小写的完成

c - 如何在c中执行任意管道并继续