c - Error during string read/write -
this question has answer here:
- implicit declaration of 'gets' 2 answers
the following program used write string file when compile using gcc shows errors
#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; }
the error when compiling
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 integer without cast [-wint-conversion] in file included expi.c:2:0: /usr/include/string.h:394:15: note: expected ‘const char *’ argument of type ‘int’ extern size_t strlen (const char *__s) ^ /tmp/cchmkvw7.o: in function `main': expi.c:(.text+0x87): warning: `gets' function dangerous , should not used.
the code not compiling text book code , not being able run . creates file doesnt add runtime text it
first of all, not use gets()
. it's dangerous function because there huge risk of overflowing array , also, removed recent c standard c11.
also, should understand how strlen()
works , how c-strings represented. you, can same as
while (strlen(string) > 0)
by writing
while (string[0] != '\0')
but need understand c-string is. , should check string
not null
pointer in both cases.
maybe want
while (fgets(s, sizeof(s), stdin) != null) ...
not fgets()
functionality of gets()
implemented in such way can safe avoiding buffer overflow.
Comments
Post a Comment