A File-copy Program in C

fputc( ) which writes characters to a file. As a practical use of these character I/O functions we can copy the contents of one file into another, as demonstrated in the following program. This program takes the contents of a file and copies them into another file, character by character.

#include "stdio.h" 
main( ) 
{ 
 FILE *fs, *ft ; 
 char ch ; 
 fs = fopen ( "pr1.c", "r" ) ; 
 if ( fs == NULL ) 
 { 
 puts ( "Cannot open source file" ) ; 
 exit( ) ; 
} 
 ft = fopen ( "pr2.c", "w" ) ; 
 if ( ft == NULL ) 
 { 
 puts ( "Cannot open target file" ) ; 
 fclose ( fs ) ; 
 exit( ) ; 
 } 
 while ( 1 ) 
 { 
 ch = fgetc ( fs ) ; 
 if ( ch == EOF ) 
 break ; 
 else 
 fputc ( ch, ft ) ; 
 } 
 fclose ( fs ) ; 
 fclose ( ft ) ; 
} 

Leave a Comment