C Program to copy a file to another file

How to write a C Program to copy a file to another file in C Programming Language ?

This C Program to copy a file to another file.

Solution:

  1. #include<stdio.h>
  2. void main()
  3. {
  4.         FILE *fp1,*fp2;
  5.         char ch;
  6.         char fname1[30],fname2[30];
  7.         printf("Enter the source file: ");
  8.         fflush(stdin);
  9.         scanf("%s",fname1);
  10.         printf("Enter the destination file: ");
  11.         fflush(stdin);
  12.         scanf("%s",fname2);
  13.         fp1=fopen(fname1,"r");
  14.         fp2=fopen(fname2,"w");
  15.         if(fp1==NULL)
  16.         {
  17.                 printf("\n cannot open file %s for reading",fname1);
  18.                 exit(1);
  19.         }
  20.         else if(fp2==NULL)
  21.         {
  22.                 printf("\n cannot open file %s for writing",fname2);
  23.                 exit(1);
  24.         }
  25.         else
  26.         {
  27.                 ch=getc(fp1);
  28.         while(ch!=EOF)
  29.         {
  30.                 putc(ch,fp2);
  31.                 ch=getc(fp1);
  32.         }
  33.         fclose(fp1);
  34.         fclose(fp2);
  35.         printf("\n files copied");
  36.         }
  37. }


Learn More :