fgets和gets之间的区别

时间:2019-03-04 15:24:36

标签: c fgets gets

我开始学习如何用C编程,我需要使用这两个函数,但我不了解两者之间的区别。

2 个答案:

答案 0 :(得分:1)

获取很危险,因为读取的字符串的长度没有保护,例如:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
      {
          options.LoginPath = new PathString("/login");
          options.Cookie.SameSite = SameSiteMode.None;
          options.Cookie.SecurePolicy = CookieSecurePolicy.None;
      });

如果您运行该程序并输入长度超过4个字符的字符串,则 s 后将写入 s ,且行为未定义

但是

#include <stdio.h>

int main()
{
  char s[5];

  if (gets(s) != NULL)
    printf("%s\n", s);
}

您确定 fgets 最多可以读取4个字符(在EOF中,末尾添加了一个空字符)

  

fgets和gets之间的区别

从不使用获取

#include <stdio.h> int main() { char s[5]; if (fgets(s, sizeof(s), stdin) != NULL) printf("%s\n", s); } 在近20年前已被弃用。

请注意,如果我编译第一个程序,编译器会警告您:

gets

但是第二个:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra g.c
g.c: In function ‘main’:
g.c:7:6: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration]
   if(gets(s) != NULL)
      ^~~~
g.c:7:14: warning: comparison between pointer and integer
   if(gets(s) != NULL)
              ^~
/tmp/ccwytkDX.o : Dans la fonction « main » :
g.c:(.text+0x14): avertissement : the `gets' function is dangerous and should not be used.

答案 1 :(得分:0)

我用C语言编写程序至少已有30年了,但是那是10年前了,所以请带一点盐。我的记忆是,在“严重”程序中,我将始终使用fgets,因为我可以指定流(文件指针)和最大缓冲区大小,并且我将在错误代码中返回有用的信息并使用{ {1}}。 _errno可能会做一些这样的事情(也许是返回值和设置gets),但是使用_errno的假设是您正在使用gets并且用户输入是“合理”,您不必担心错误,而错误通常是未来灾难的一个公式。基本上,我只在很小的玩具程序上使用了stdin,但从未用于工业用途。实际上,我非常不信任gets,我也没有真正将其用于自己的小玩具程序。我只是习惯使用gets并坚持使用它。