File-copy Program in C

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 ) ; 
}

Writing to a File

The fputc( ) function is similar to the putch( ) function, in the sense that both output characters. However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. Which file? The file signified by ft. The writing process continues till all characters from the source file have been written to the target file, following which the while loop terminates

Leave a Comment