【Linux-c編程】實現簡單的cp命令


 

  1 #define _LARGEFILE_SOURCE          //1-3:定義宏:才能讓系統支持大於2GB文件復制操作。

  2 #define _LARGEFILE64_SOURCE
  3 #define _FILE_OFFSET_BITS 64
  4 #include<stdio.h>
  5 #include<string.h>
  6 #include<stdlib.h>
  7 #include<fcntl.h>
  8
  9 int main(int argc,char *argv[])
 10 {
 11         int fd_src,fd_des;
 12         char buf[128];
 13         int num;
 14         if(argc-3)                                                                            //如果參數格式不是 cp  file_src  file_des,則報錯退出。
 15         {
 16                 printf("the format must be:cp file_src file_des");
 17                 exit(EXIT_FAILURE);
 18         }
 19
 20         if((fd_src=open(argv[1],O_RDONLY))==-1)                             // 如果文件不存在,則報錯退出。
 21         {
 22                 perror("open1");
 23                 exit(EXIT_FAILURE);

             }
 25
 26         if((fd_des=open(argv[2],O_CREAT|O_EXCL|O_WRONLY,0644))==-1)// 以寫的方式打開文件,O_EXCl:如果目標文件存在,報錯。
 27         {
 28                 perror("open2");
 29                 exit(EXIT_FAILURE);
 30         }
 31
 32         do                                                     
 33         {
 34                 num=read(fd_src,buf,128);              //讀源文件
 35                 write(fd_des,buf,num);                // 寫入目標文件
 36         }while(num==128);


 37         close(fd_src);
 38         close(fd_des);                                                                  //關閉文件
 39         return 0;
 40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM