为什么与fgets函数去precated? [英] Why is the fgets function deprecated?

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

问题描述

的GNU C编程教程:

与fgets (文件中获得串)的功能类似于变
  功能。此功能的德precated 的 - 这意味着它已经过时了
  并强烈建议您不要使用它 - 因为它是
  危险的。因为如果输入数据包含空有危险
  性格,你不能告诉。不要使用与fgets ,除非你知道数据
  不能包含空。不要使用它来读取用户编辑文件
  因为,如果用户插入一个空字符,就应该把
  妥善处理或打印一个明确的错误信息。始终使用
  函数getline 或者,如果你能 getdelim 而不是与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.

我想,当它遇到一个 \\ 0 \\ n中的与fgets 函数停止;为什么会发生这种手册建议空字节是危险的时候与fgets 要正确处理输入?此外,就是函数getline 与fgets 之间的差异,是与fgets 函数真正考虑的德precated在的在 C99 或将来的C标准?

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 是C99还是目前的标准,C11 pcated没有真正去$ P $。但是,该教程的作者是正确的,当它遇到一个NUL,并且没有机制报告其这样的性格读与fgets 不会停止。

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 指定的字符数少至多一个
  从流指向进入阵列由取值指出。没有额外的字符后换行字符(保持不变)或之后结束的文件中读取。

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的 getdelim 函数getline 已在 2008年POSIX ,因此,如果您指定了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.

修改我想,绝对没有安全中的NULL字符脸使用与fgets 的方式,但ř。(见注释)指出有:

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, '\n', sizeof(buf));  // fgets will never write a newline
fgets(buf, sizeof(buf), fp);

现在寻找的最后一个非 - \\ n BUF 字符。我不会真的建议此杂牌组装电脑,虽然。

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

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

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