I wrote the following code to copy the text file to another:
FILE *fpr, *fpw;
int ch;
fpr = fopen("M.txt","r");
fpw = fopen("P.txt","w");
if(fpr == NULL)
printf("File open failed!");
else
{
while(1)
{
ch = fgetc(fpr);
if(ch == EOF)
break;
fputc(ch, fpw);
}
fclose(fpr);
fclose(fpw);
printf("Successfully copied!");
}
It worked perfectly. Then I changed int ch to char ch it also worked for me. But when i used the following code for copying a .exe file, file copying is not working correctly.
FILE *fpr, *fpw;
char ch;
fpr = fopen("M.exe","rb");
fpw = fopen("P.exe","wb");
if(fpr == NULL)
printf("File open failed!");
else
{
while(1)
{
ch = fgetc(fpr);
if(ch == EOF)
break;
fputc(ch, fpw);
}
fclose(fpr);
fclose(fpw);
printf("Successfully copied!");
}
I changed char ch to int ch then it's working fine! Why this happens with binary files not with text file? What happens when char ch was used in the case of binary?
Please help...
Thank you for your feed back in advance.
It's because EOF is probably 0 or 255 for char which can show up in middle of binary file but can't in text file(that's why only text file work for char). However EOF is -1 for int which can't show up in middle of a file no matter what(only 0-255 inclusive can).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With