Well, I see several problems in your code but the most important one is that the expression:
(c=getc(f1))!=EOF
Will always evaluated true, so you'll run infinite loops. If you read getc
documentation you'll realize that it returns an int
not a char
:
So basically what you're doing is truncating the EOF
, which is an int
generally defined as -1, to a char
when:
c=getc(f1) // At this point C = 255(0xFF) if getc returned EOF
And then promoting c
to an int
when is compared to EOF
, since an int
is big
enough to hold 255 the comparison made is 255 != -1, which is always true.
To fix that just declare c
as an int
.
Some more tips:
You may also want to make sure that it was an end of file condition by using feof
since getc
returns EOF
on other error conditions as well.
You may want to move the "\n"
to the end of your senteces on printf
calls to force a flush on stdout. Or alternatively you can add this at the start of your program:
setvbuf(stdout, 0, _IONBF, 0);
It seems you're storing the file names in name1
and name2
, so you may want to remove the double quotes from fopen
file names so that it actually use them.
When you open name2
you use write access only but at the end you try to read and display its content, you may want to use "w+"
as the access mode.
When you're trying to print the resulting data the file handler in f2
has already been closed. And the file cursors are already at the end of the file so you may want to use rewind
, e.g.
//fclose(f2);
rewind(f1);
rewind(f2);
printf("The data in the source file is :\n");
while((c=getc(f1))!=EOF)
{
printf("%c",c);
}
printf("The data in the destination file is :\n");
while((c=getc(f2))!=EOF)
{
printf("%c",c);
}
fclose(f1);
fclose(f2);