The 'copy file' problem illustrates the feof() problem
Code:
#include <stdio.h>
// this works
void good ( char *in, char *out ) {
FILE *fin = fopen( in, "r" );
FILE *fout= fopen( out,"w" );
int ch;
while ( (ch=fgetc(fin)) != EOF ) {
fputc(ch,fout);
}
fclose(fin);
fclose(fout);
}
// this appends an extra char - specifically (char)EOF
// to the output file
// feof() returns true only AFTER a read function has returned EOF
void bad ( char *in, char *out ) {
FILE *fin = fopen( in, "r" );
FILE *fout= fopen( out,"w" );
int ch;
while ( !feof(fin) ) {
ch = fgetc(fin);
fputc(ch,fout);
}
fclose(fin);
fclose(fout);
}
// this works, but looks less tidy
void ugly ( char *in, char *out ) {
FILE *fin = fopen( in, "r" );
FILE *fout= fopen( out,"w" );
int ch;
while ( !feof(fin) ) {
ch = fgetc(fin);
if ( ch != EOF ) {
fputc(ch,fout);
}
}
fclose(fin);
fclose(fout);
}
int main ( ) {
good( "sample.txt", "good.txt" );
bad( "sample.txt", "bad.txt" );
ugly( "sample.txt", "ugly.txt" );
return 0;
}