2016-09-13 33 views
-3

下面的程序是用來當我編譯使用gcc它顯示了錯誤錯誤/寫

將字符串寫入文件
#include<stdio.h> 
#include<string.h> 
#include <stdlib.h> 

int main() { 
    FILE *fp; 
    char s[80]; 
    fp = fopen("POEM.TXT", "w"); 
    if(fp == NULL) { 
     puts("Cannaot open file"); 
     exit(1); 
    } 
    printf("\n Enter"); 
    while(strlen(gets(s)) > 0) { 
     fputs(s, fp); 
     fputs("\n", fp); 
    } 
    fclose(fp); 
    return 0; 
} 

當我編譯錯誤是

gcc expi.c 
expi.c: In function ‘main’: 
expi.c:18:14: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration] 
while(strlen(gets(s))>0) 
      ^
expi.c:18:14: warning: passing argument 1 of ‘strlen’ makes pointer from integer without a cast [-Wint-conversion] 
In file included from expi.c:2:0: 
/usr/include/string.h:394:15: note: expected ‘const char *’ but argument is of type ‘int’ 
extern size_t strlen (const char *__s) 
      ^
/tmp/ccHMKvW7.o: In function `main': 
expi.c:(.text+0x87): warning: the `gets' function is dangerous and should not be used. 

代碼不編譯它是教科書代碼,我無法運行它。它創建一個文件,但它不會將運行時文本添加到它

+0

@PaulRooney:C中的警告通常就像其他語言中的錯誤。他們應該得到解決。 'gets'不是C標準的一部分(因爲C11,自C99以來已棄用),原因很充分。 – Olaf

+0

@PaulRooney:這是錯的!由於缺少聲明,C會回退到遺留函數類型,其中包括潛在的有問題的強制。所以試圖運行你得到警告的代碼通常是一個壞主意。有趣的是,即使鏈接器警告這個功能。 – Olaf

+0

請拿一本更好的書。你的編譯器很清楚地告訴你,'gets is bad'。 –

回答

-1

首先,不要使用gets()。這是一個非常危險的功能,因爲存在溢出陣列的巨大風險,並且它從最近的標準中被刪除。

另外,您應該瞭解strlen()如何工作以及如何代表。你,可以做完全一樣

while (strlen(string) > 0) 

僅通過寫

while (string[0] != '\0') 

但你需要了解是什麼。在這兩種情況下,您應該檢查string不是NULL指針。

也許這是你想要的

while (fgets(s, sizeof(s), stdin) != NULL) ... 

不是fgets()基本上是這樣一種方式,它可以安全避免緩衝區溢出實施gets()的功能。

+1

'gets'已在**之前的**標準(C99)中棄用。它已從C11標準中刪除。 (afaik它是唯一被刪除的函數)。 – Olaf