Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit declaration of 'gets'

Tags:

c

linux

gets

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);
   }
}
like image 744
Death_by_Ch0colate Avatar asked Dec 01 '15 22:12

Death_by_Ch0colate


2 Answers

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.

like image 93
P.P Avatar answered Nov 09 '22 04:11

P.P


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);
    }
}
like image 22
chqrlie Avatar answered Nov 09 '22 02:11

chqrlie