"获取"的隐含声明

Dea*_*ate 9 c linux gets

我理解"隐式声明"通常意味着在调用函数之前必须将函数置于程序的顶部,或者我需要声明原型.
但是,gets应该在stdio.h文件中(我已经包含在内).
有没有什么办法解决这一问题?

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   char ch, file_name[25];
   FILE *fp;

   printf("Enter the name of file you wish to see\n");
   gets(file_name);
   fp = fopen(file_name,"r"); // read mode
   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 18

你是对的,如果你包含正确的标题,你不应该得到隐式声明警告.

然而,该功能gets()已被删除,从C11的标准.这意味着不再有一个原型gets()<stdio.h>.gets() 曾经<stdio.h>.

删除的原因gets()是众所周知的:它无法防止缓冲区溢出.因此,您应该永远不要使用gets()和使用fgets()并处理尾随换行符(如果有的话).

  • 这可能是因为库仍然具有该功能,可能是为了避免破坏古老的代码。但是任何新代码都不应该使用“gets()”。 (2认同)

chq*_*lie 13

gets()从C11标准中删除.不要使用它.这是一个简单的替代方案:

#include <stdio.h>
#include <string.h>

char buf[1024];  // or whatever size fits your needs.

if (fgets(buf, sizeof buf, stdin)) {
    buf[strcspn(buf, "\n")] = '\0';
    // handle the input as you would have from gets
} else {
    // handle end of file
}
Run Code Online (Sandbox Code Playgroud)

您可以将此代码包装在函数中,并将其用作以下代码的替代gets:

char *mygets(char *buf, size_t size) {
    if (buf != NULL && size > 0) {
        if (fgets(buf, size, stdin)) {
            buf[strcspn(buf, "\n")] = '\0';
            return buf;
        }
        *buf = '\0';  /* clear buffer at end of file */
    }
    return NULL;
}
Run Code Online (Sandbox Code Playgroud)

并在您的代码中使用它:

int main(void) {
    char file_name[25];
    FILE *fp;

    printf("Enter the name of file you wish to see\n");
    mygets(file_name, sizeof file_name);
    fp = fopen(file_name, "r"); // read mode
    if (fp == NULL) {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }
}
Run Code Online (Sandbox Code Playgroud)