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 <stdlib.h>

int main() {
FILE *fp;
char s[80];
fp = fopen("POEM.TXT", "w");
if(fp == NULL) {
puts("Cannaot open file");
printf("\n Enter");
while(strlen(gets(s)) > 0) {
fputs(s, fp);
fputs("\n", 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]
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download