venuturumilli Sita Rama Rao venuturumilli Sita Rama Rao - 2 months ago 13
C Question

Error during string read/write

The following program is used to write a string to a file
When I compile using gcc it shows the 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 i am compiling is

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.

Answer

First of all, DO NOT USE gets(). It's a very dangerous function because there is a huge risk of overflowing the array and also, it was removed from recent standard .

Also, you should understand how strlen() works and how are represented. You, can do exactly the same as

while (strlen(string) > 0)

by just writing

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

but for that you need to understand what a is. And you should check that string is not a NULL pointer in both cases.

Maybe this is what you want

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

not that fgets() is basically the functionality of gets() implemented in such a way that it can be safe avoiding buffer overflow.