Thursday, February 2, 2012

C Program - Copy data from a file to another

copy.c SYNTAX: copy file1 file2 file1 - file to be copied file2 - file on to which file1 is to be copied copies file1 to file2 after creating file2. if already existing it rewrites the oldfile with the new file remarks 1. error checking is done 2. if file1 is not present it shows error 3. working for files in the same directory as well as files in other directories 4. copies in blocks of 1024 bytes buffer size is 1024 5. if file2 is not present it creates a file if already present it over writes
 #include<unistd.h>  
 #include<fcntl.h>  
 #include<stdlib.h>  
 #include<sys/stat.h>  
 #include<stdio.h>  
 #include<error.h>  
 #include<errno.h>  
 int main(int argc, char *argv[])  
 {  
      char block[1024];  
      int in, out;  
      size_t rlen,wlen;  
      char *filein;  
      char *fileout;  
      filein=argv[1];  
      fileout=argv[2];  
      //     printf("%s\n",filein);  
      //     printf("%s\n",fileout); //prints the file names of file 1,2  
      in=open(filein,O_RDONLY);  
      out=open(fileout,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);//creates o/p file if not present  
      //     printf("File descriptor\n1.IN file:\t%d\n2.OUT file:\t%d\n",in,out); //prints the file descriptors   
      if(in==-1|out==-1)  
       {  
        if(in==-1)  
         error(1,0,"input file not present");// if ip file not present  
        if(out==-1)  
         error(1,0,"output file cannot be opened");//op file problem  
        exit(1);  
       }  
      while((rlen=read(in,block,sizeof(block)))>0)  
      {  
       //printf("read length:\t%d\n",rlen);  
           write(out,block,rlen);  
      }  
      printf("Copy from %s to %s Successful\n",argv[1],argv[2]);  
      return 0;  
 }  

No comments:

Post a Comment