0

This is a program for copying content from one file to other file. How to specify EOF in online compiler so that my code will run as expected??

Link for online editor---> https://www.jdoodle.com/c-online-compiler

//code for copying content--->>

#include "stdio.h"

int main()
{
char ch;
FILE *p,*q;
p=fopen("data.txt","w");
while(ch=getchar()!=EOF)
{
    putc(ch,p);
}

fclose(p);
p=fopen("data.txt","r");
q=fopen("newdata.txt","w");
while(ch=getc(p)!=EOF)
{
    putc(ch,q);
}

fclose(p);
fclose(q);
q=fopen("newdata.txt","r");
while(ch=getc(q)!=EOF)
{
    printf("\n%c",ch);
}

}

1 Answers1

2

There are two problems with the expression ch=getchar()!=EOF:

  1. The first is that getchar returns an int. This is actually important for the EOF comparison.

  2. The second problem is about operator precedence. You expression is really ch = (getchar() != EOF). That is, you assign the result of the comparison (which is an 1 or 0) to the variable ch.

To solve the first problem, define the variable ch as an int.

To solve the second problem use explicit parentheses: (ch = getchar()) != EOF.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621