-3

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.

the code is not compiling it is text book code and i am not being able to run it . it creates a file but it doesnt add runtime text to it

1 Answers1

0

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 1
    `gets` has been deprecated in the **previous** standard (C99). It has been removed from the standard with C11. (afaik it is the only function which has been removed). – too honest for this site Sep 13 '16 at 00:53