File Handling: Copy Content of One File to Another in C

  1. /* 
  2.   Name: SHANAWAR 
  3.   Copyright:  
  4.   Description:   PROGRAM THAT READS DATA FROM ONE FILE AND WRITE IT ON ANOTHER FILE.  
  5. */  
  6.   
  7. #include<stdio.h>  
  8. #include<conio.h>  
  9.   
  10. int main()  
  11. {  
  12.     FILE *fr,*fw;  // file pointers  
  13.   
  14.     char fname[20],fname2[20],str[80];  
  15.   
  16.     printf("Source file name");  
  17.   
  18.     gets(fname);  
  19.   
  20.     // fopen( file_name , mode)  
  21.      
  22.     if( ( fr = fopen(fname,"r") ) == NULL )  // "r" represents read mode  
  23.     {  
  24.   
  25.       // if fr is equals to NULL it means file can't open        
  26.   
  27.       printf("File Can't Open");  
  28.       return 1;  
  29.   
  30.     }  
  31.      
  32.     printf("Enter Target file name");  
  33.   
  34.     gets(fname2);  
  35.       
  36.     if( ( fw = fopen(fname2,"a") ) == NULL) // "a" represents append mode  
  37.     {  
  38.   
  39.       // if fw is equals to NULL it means file can't open  
  40.   
  41.       printf("File Can't Open");  
  42.       return 1;  
  43.   
  44.     }  
  45.      
  46.     while( fgets(str,80,fr) != NULL )   // reading strings from source file  
  47.     {  
  48.   
  49.      fputs(str,fw);  // writing strings into target file  
  50.   
  51.     }  
  52.       
  53.      // close opened files  
  54.    
  55.      fclose(fr);  
  56.      fclose(fw);  
  57.        
  58.      getch();  
  59.      return 0;  
  60. }  
  61.        
  62.