Copy a Text File - C File

C examples for File:File Operation

Description

Copy a Text File

Demo Code

#include <stdio.h>

int main()//from   w  ww. j  a v  a2s .c o m
{
     FILE *fptrSource, *fptrTarget;
     int m, n, p;
    
     fptrSource = fopen("C:\\Code\\data.txt", "r");
     if(fptrSource == NULL){
          puts("Source-file-opening failed");
          return (1);
     }
     puts("Source-file data.txt opened successfully");
    
     fptrTarget = fopen("C:\\Code\\town.dat", "w");
     if(fptrTarget == NULL){
          puts("Target-file-opening failed");
          return (2);
     }
     puts("Target-file town.dat opened successfully");
    
     m = fgetc(fptrSource);
    
     while(m != EOF){
          fputc(m, fptrTarget);
          m = fgetc(fptrSource);
     }
    
     puts("File copied successfully");
    
     n = fclose(fptrSource);
     if(n == -1)
         puts("Source-file-closing failed");
     if(n == 0)
         puts("Source-file closed successfully");
    
     p = fclose(fptrTarget);
     if(p == -1)
         puts("Target-file-closing failed");
     if(p == 0)
         puts("Target-file closed successfully");
    
     return(0);
}

Result


Related Tutorials