Friday, November 4, 2011

A File-copy Program in C programming

We have already used the function fgetc( ) which reads characters from a file. Its counterpart is a function called 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" ) ;}
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 ) ;
}

I hope most of the stuff in the program can be easily understood, since it has already been dealt with in the earlier section. What is new is only the function fputc( ). Let us see how it works.
exit( ) ;

No comments:

Post a Comment