Implicit declaration of 'gets'

人走茶凉 提交于 2019-11-27 19:19:11

问题


I understand that an 'implicit declaration' usually means that the function must be placed at the top of the program before calling it or that I need to declare the prototype.
However, gets should be in the stdio.h files (which I have included).
Is there any way to fix this?

#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);
   }
}

回答1:


You are right that if you include proper headers, you shouldn't get the implicit declaration warning.

However, the function gets() has been removed from C11 standard. That means there's no longer a prototype for gets() in <stdio.h>. gets() used to be in <stdio.h>.

The reason for the removal of gets() is quite well known: It can't protect against the buffer overrun. As such, you should never use gets() and use fgets() instead and take care of the trailing newline, if any.




回答2:


gets() was removed from the C11 standard. Do not use it. Here is a simple alternative:

#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
}

You can wrap this code in a function and use that as a replacement for 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;
}

And use it in your code:

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);
    }
}


来源:https://stackoverflow.com/questions/34031514/implicit-declaration-of-gets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!