【问题标题】:fgets - Take null character into accountfgets - 考虑空字符
【发布时间】:2021-06-22 11:34:26
【问题描述】:

当使用int scanf(const char *format, ...) 扫描用户输入时,我会读取比字符串大小少一个字符,因为字符串的最后一个字符必须是null character \0

char str[10];
scanf("%9s", str); /* take \0 into account */

但是当我使用char *fgets(char *str, int n, FILE *stream) 时,我不知道我应该如何指定n。大多数在线教程都设置为sizeof(str),但有人告诉我应该是sizeof(str) - 1

那么如何防止缓冲区溢出呢?像这样:

char str[10];
fgets(str, 10, stdin);

或者我应该这样做:

char str[10];
fgets(str, 9, stdin);

【问题讨论】:

  • 第一个,fgets 使用最后一个元素来终止字符串。是的,推荐的用法是fgets(str, sizeof str, stdin);
  • @anastaciu 好的,谢谢!

标签: c string stdin fgets null-character


【解决方案1】:

C11 7.21.7.2(强调我的):

  1. fgets 函数最多读取比n 指定的字符数少一个 [...] 在读入数组的最后一个字符之后立即写入一个空字符。
  2. [如果发生错误]返回一个空指针。

因此,正确的用法是使用数组的完整大小检查返回值。

char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) /* all bets are off */;

【讨论】:

  • 注意:返回NULL 的另外两个原因:文件结束指示符指示符已设置并且在读取任何数据之前发生文件结束。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 2012-07-10
  • 2021-08-15
相关资源
最近更新 更多