C Program to Copy One File to Another File

«
»
This C Program copies a file into another file.

Here is source code of the C Program to copy a file into another file. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Copy a File into Another File
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main(int argc,char **argv)
  7. {
  8.     FILE *fp1, *fp2;
  9.     char ch;
  10.     int pos;
  11.  
  12.     if ((fp1 = fopen(argv[1],"r")) == NULL)    
  13.     {    
  14.         printf("\nFile cannot be opened");
  15.         return;
  16.     }
  17.     else     
  18.     {
  19.         printf("\nFile opened for copy...\n ");    
  20.     }
  21.     fp2 = fopen(argv[2], "w");  
  22.     fseek(fp1, 0L, SEEK_END); // file pointer at end of file
  23.     pos = ftell(fp1);
  24.     fseek(fp1, 0L, SEEK_SET); // file pointer set at start
  25.     while (pos--)
  26.     {
  27.         ch = fgetc(fp1);  // copying file character by character
  28.         fputc(ch, fp2);
  29.     }    
  30.     fcloseall();    
  31. }

$ cc file1.c
$ a.out /tmp/vmlinux mylinux
 
File opened for copy...
 
$cmp /tmp/vmlinux mylinux
 
$ ls -l mylinux
-rw-rw-r--. 1 adi adi 3791744 Jul 27 19:57 mylinux

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.