Copying One File to another in C

Copying One File to another in C

This is a simple C program that copies the contents of one ASCII (text) file onto another file. It is similar to Unix’s

cp

  command.

This C program is called with two parameters i.e. the names of two files (fin and fout). The contents of the file referenced in second parameter are copied onto the file which is referenced by first parameter.

#include <stdio.h>

int main(int argc, char * argv[]){
  FILE *fin, *fout;
  char c;

  if (argc!=3){
    printf("Usage: %s fileout filein\n", argc);
    exit(0);
  }
  if ((fin=fopen(argv[2],"r"))==NULL){
    perror("fopen filein");
    exit(0);
  }
  if ((fout=fopen(argv[1],"w"))==NULL){
    perror("fopen fileout");
    exit(0);
 }

  while ((c=getc(fin))!=EOF)
  putc(c,fout);

  fclose(fin);
  fclose(fout);
}

 

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post