C Program to Copy File into 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.

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

If you wish to look at programming examples on all topics, go to C Programming Examples.
Subscribe Newsletter & Posts
About

Manish Bhojasia, a technology veteran with 17+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer and SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage & Cluster Administration, Advanced C Programming, SAN Storage Technologies, SCSI Internals and Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him below.


Sanfoundry Training Center of Excellence (CoE)

Manish Bhojasia, a technology veteran with 17+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer and SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage & Cluster Administration, Advanced C Programming, SAN Storage Technologies, SCSI Internals and Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him below.


Follow Manish & Sanfoundry