为什么不推荐使用 fgets 函数? [英] Why is the fgets function deprecated?

查看:33
本文介绍了为什么不推荐使用 fgets 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自GNU C 编程教程:

fgets(文件获取字符串")函数类似于gets功能.此函数已弃用 -- 这意味着它已过时强烈建议您不要使用它——因为它是危险的.这是危险的,因为如果输入数据包含空值性格,你看不出来.除非你知道数据,否则不要使用 fgets不能包含空值.不要用它来读取用户编辑的文件因为,如果用户插入空字符,您应该正确处理或打印清晰的错误信息.一直使用如果可以,getlinegetdelim 代替 fgets.

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 函数在遇到 时会停止;当 fgets 应该正确处理输入时,为什么本手册页建议空字节是危险的"?此外,getlinefgets 之间有什么区别,fgets 函数是否真正被视为 deprecatedstrong>C99 还是未来的 C 标准?

I thought the fgets function stops when it encounters a or ; 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 实际上并未在 C99 或当前标准 C11 中弃用.但是那个教程的作者是对的,fgets 在遇到 NUL 时不会停止,并且没有报告它读取这样一个字符的机制.

No, fgets is not actually deprecated in C99 or the current standard, C11. But the author of that tutorial is right that fgets will not stop when it encounters a NUL, and has no mechanism for reporting its reading of such a character.

fgets 函数读取最多比 n 指定的字符数少 1从stream指向的流到s指向的数组.在换行符(保留)或文件结束符之后不读取其他字符.

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 节)

(§7.21.7.2)

GNU 的 getdelimgetline 已在 POSIX 2008,所以如果您的目标是 POSIX 平台,那么使用它们可能不是一个坏主意.

GNU's getdelim and getline have been standardized in POSIX 2008, so if you're targeting a POSIX platform, then it might not be a bad idea to use those instead.

编辑我认为在 NUL 字符面前绝对没有安全的方法使用 fgets,但是 R..(见评论)指出:

EDIT I thought there was absolutely no safe way to use fgets in the face of NUL characters, but R.. (see comments) pointed out there is:

char buf[256];

memset(buf, '
', sizeof(buf));  // fgets will never write a newline
fgets(buf, sizeof(buf), fp);

现在在 buf 中查找最后一个非 字符.不过,我实际上不会推荐这种混搭.

Now look for the last non- character in buf. I wouldn't actually recommend this kludge, though.

这篇关于为什么不推荐使用 fgets 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆