实现Linux下的cp命令

cp命令的作用:读取源文件写到目标文件

具体实现思路:

1.打开源文件,先判断argc==3,argv[0]为可执行程序的名字,argv[1]为源文件,argv[2]为目标文件

2.当源文件存在的时候用O_EXCL进行一次提示

3.当源文件与目标文件都正确打开后,循环读取源文件写入目标文件

4.完成实现后可以用vimdiff  文件A  文件B 可以比较两个文件相同与否

具体实现代码:

  1 #include<stdio.h>                                                           
  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 #include<fcntl.h>
  5 #include<errno.h>
  6 #include<string.h>
  7 int main(int argc,char *argv[])
  8 {
  9     if(argc!=3)
 10     {
 11         fprintf(stderr,"usage:%s src dst\n",argv[0]);
 12         exit(1);
 13     }
 14     int fd_src=open(argv[1],O_RDONLY);
 15     if(fd_src==-1)
 16     {
 17         perror("open");
 18         exit(1);
 19     }
 20     int fd_dest=open(argv[2],O_WRONLY|O_CREAT|O_EXCL,0644);
 21     if(fd_dest==-1&&errno==EEXIST)
 22     {
 23         printf("recover it?");
24         char choose;
 25         scanf("%c",&choose);
 26         if(choose=='y'||choose=='Y')
 27         {
 28             fd_dest=open(argv[2],O_WRONLY);
 29         }
 30         else
 31         {
 32             exit(1);
 33         }
 34     }
 35     while(1)
 36     {
 37         char buf[1024]={};
 38         memset(buf,0x00,sizeof(buf));
 39         int r=read(fd_src,buf,1024);
 40         if(r==-1)
 41         {                                                                   
 42             perror("read");
 43             exit(1);
 44         }
 45         if(r==0)
 46         {
 47             break;
 48         }
 49         write(fd_dest,buf,r);
 50     }
 51     close(fd_src);
 52     close(fd_dest);
 53 }                       

猜你喜欢

转载自blog.csdn.net/enjoymyselflzz/article/details/81334215