#include #include /* Copy From Sourcefile To Destfile And return The Number */ /* Of Characters Copied; -1 For Errors */ int copy1( const char *destFile, const char *sourceFile ) { int charsCounted = 0; int ch; FILE *sfp, *dfp; if( strcmp( sourceFile, destFile ) == 0 ) { printf( "Can not copy to self\n" ); return -1; } if( ( sfp = fopen( sourceFile, "r" ) ) == NULL ) { printf( "Can not open input file %s\n", sourceFile ); return -1; } if( ( dfp = fopen( destFile, "w" ) ) == NULL ) { printf( "Cannot open output file %s\n", destFile ); fclose( sfp ); return -1; } while( ( ch = getc( sfp ) ) != EOF ) if( putc( ch, dfp ) == EOF ) { printf( "Unexpected error during write.\n" ); break; } else charsCounted++; fclose( sfp ); fclose( dfp ); return charsCounted; } #define MAX_LINE_LEN 256 int copy2( const char *destFile, const char *sourceFile ) { int charsCounted = 0; char oneLine[ MAX_LINE_LEN + 2 ]; FILE *sfp, *dfp; if( strcmp( sourceFile, destFile ) == 0 ) { printf( "Can not copy to self\n" ); return -1; } if( ( sfp = fopen( sourceFile, "r" ) ) == NULL ) { printf( "Can not open input file %s\n", sourceFile ); return -1; } if( ( dfp = fopen( destFile, "w" ) ) == NULL ) { printf( "Cannot open output file %s\n", destFile ); fclose( sfp ); return -1; } while( ( fgets( oneLine, MAX_LINE_LEN, sfp ) ) != NULL ) if( fputs( oneLine, dfp ) < 0 ) { printf( "Unexpected error during write.\n" ); break; } else charsCounted += strlen( oneLine ); fclose( sfp ); fclose( dfp ); return charsCounted; } int main( ) { int chars1 = 0; int chars2 = 0; chars1 = copy1( "out1.txt", "in.txt" ); printf( "%d characters copied\n", chars1 ); chars2 = copy2( "out2.txt", "in.txt" ); printf( "%d characters copied\n", chars2 ); }