Computer Concept & Programming In C - Unit V - 9

Q.24 Write a C program to copy the contents of one file to another.  (AKTU. 2008 - 09)
Or.      Write a program in C to copy the text of one file to another.     (AKTU. 2010 - 11)
Ans.
#include<stdio.h>
#include<conio.h>
void main()
{
 FILE *rfp;   /* Reading file pointer */
 FILE *wfp;   /* Writing file pointer */
 char c[50], a ;
 clrscr();

 /* Step -1 Writing to a file initially say read.txt */
if( ( rfp = fopen("read.txt","w"))!= NULL)
   {
      printf("\nStart writing the contents of the file\n");
      while(1)
      {
         printf("\n Do you want to write more contents y/n\n ");
a = getche();
printf("\n Start--->");
if((a == 'n')||(a =='N'))
  break;
gets(c);
fputs(c,rfp);

      }
      fclose(rfp);
    }
else
   printf("\nError opening the file");
printf("\nPress any key to start writing to another file.");
getch();
/*Step - 2 Read the input from the previous file
  and  write it into a new file
  say  write.txt*/
printf("\n The contents  you wrote in the read.txt file");
printf("\nwill now be written to the write.txt file and");
printf("\n both read.txt and write.txt are present in bin folder");
if((rfp = fopen("read.txt","r"))!= NULL)
 {
   if((wfp = fopen("write.txt","w"))!= NULL)
    {
      char c;
      do
{
 c = fgetc(rfp);  /* reads one character from read.txt*/
 fputc(c,wfp);    /* writes one character to write.txt*/
}
       while( c != EOF);
       fclose(wfp);
     }
    else
       printf("\nError opening write.txt file");
  }
  else
  printf("\nError opening the read.txt file");
printf("\n Press any key to exit.");
getch();
}