下面的程序是用來當我編譯使用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.
代碼不編譯它是教科書代碼,我無法運行它。它創建一個文件,但它不會將運行時文本添加到它
@PaulRooney:C中的警告通常就像其他語言中的錯誤。他們應該得到解決。 'gets'不是C標準的一部分(因爲C11,自C99以來已棄用),原因很充分。 – Olaf
@PaulRooney:這是錯的!由於缺少聲明,C會回退到遺留函數類型,其中包括潛在的有問題的強制。所以試圖運行你得到警告的代碼通常是一個壞主意。有趣的是,即使鏈接器警告這個功能。 – Olaf
請拿一本更好的書。你的編譯器很清楚地告訴你,'gets is bad'。 –