2015-12-01 135 views
2

我明白'隱式聲明'通常意味着函數在調用之前必須放在程序的頂部,或者我需要聲明原型。
但是,gets應該在stdio.h文件(我已包括)。
有什麼辦法解決這個問題嗎?隱式聲明'gets'

#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

請顯示您的代碼。 – kaylum

+1

你的代碼是什麼?你如何編譯它,你使用的理由是什麼? – PSkocik

+1

查看http://stackoverflow.com/help/mcve獲取關於如何生成示例代碼的靈感 –

回答

10

你說得對,如果你包含正確的頭文件,你不應該得到隱含的聲明警告。

但是,功能gets()已從012標準中刪除從012標準的。這意味着中不再有gets()的原型。 gets()用於<stdio.h>

刪除gets()的原因是衆所周知的:它不能防止緩衝區溢出。因此,您絕對不應該使用gets()並使用fgets()來代替尾隨的換行符(如果有的話)。

+0

(如果您沒有入侵)奇怪的部分是,即使它給出了錯誤,它仍然能夠正常運行。 –

+0

這可能是因爲圖書館仍然有這個功能,可能是爲了避免破壞古代代碼。但是沒有新的代碼應該使用'gets()'。 –

6

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 
} 

你可以在一個函數包裝這個代碼,並以此作爲對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; 
} 

而在你的代碼中使用它:

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