0

I'm trying to write data into a file using C. I wrote the below code.

#include<stdio.h>

void main(){

    FILE *f1;
    char c;

    printf("Data Input\n\n");
    f1 = fopen("INPUT", "w");

    while((c = getchar()) != EOF)   putc(c, f1);

    fclose(f1);

    printf("\nData Output\n\n");
    f1 = fopen("INPUT", "r");

    while((c=getc(f1)) != EOF)  printf("%c", c);
    fclose(f1);

}

But the code is behaving abnormally. The below pic is the output. enter image description here

I had to enter EOF three times to make it work. I don't understand why this is happening. Is there any error in my code? I'm using Dev-C++ 5.6.3

Thanks in advance.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 1
    **Note:** `void main()` is an anachronism. The proper definitions of `main()` are `int main (void)` and `int main (int argc, char **argv)`. You will also see the equivalent, and proper, `int main (int argc, char *argv[])`. There are non-standard OS specific parameter extensions, e.g. `char **envp`, but those should not be used for portable code. – David C. Rankin Mar 10 '17 at 14:26
  • Why do you use `putc` to write to f1, but `printf` to write to stdout? It would be more consistent to use `putc(c, stdout)` – William Pursell Mar 10 '17 at 14:27

1 Answers1

1

If char is unsigned on your platform it cannot store EOF and the comparison will never become true.

Change

char c;

to

int c;
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82