Monday, 25 August 2014

Filled Under:

C Program to Copy File into Another File

Share
Here is C Program to Copy File into Another File is given below which copy the data of first file into second file.First it open both file in read and write mode simultaneously.For performing this task it uses two file handling function fgetc() and fputc().

C Program to Copy File into Another File

C Program to Copy File into Another File



#include<stdio.h>
#include<process.h>
void main() {
   FILE *fp1, *fp2;
   char a;
   clrscr();
   fp1 = fopen("test.txt", "r");
   if (fp1 == NULL) {
      puts("cannot open this file");
      exit(1);
   }
   fp2 = fopen("test1.txt", "w");
   if (fp2 == NULL) {
      puts("Not able to open this file");
      fclose(fp1);
      exit(1);
   }
   do {
      a = fgetc(fp1);
      fputc(a, fp2);
   } while (a != EOF);
   fcloseall();
printf("\n Content will be written successfully to file");
   getch();
}

Output

Content will be written successfully to file


Explanation :


The idea behind copy the content of one file into another is very simple,the file which contains the content will be open in read mode and the file in which we want to copy the contents will be open in write mode.Then by using fgetc() function get the character from first file and simultaneously write this character into second file by using fputc() until the end of the file.