Linux文件复制cp命令的实现

Linux命令cp的实现
代码如下:

#include 
#include 
#include 
#include 
#include 

#define SIZE 8192

int main(int argc, char *argv[])
{
    char buf[SIZE];
    int fd_src, fd_dest, len;
    //参数错误,退出
    if(argc < 3){
        printf("args error\n");
        exit(1);
    }    
    //源文件只读打开
    fd_src = open(argv[1], O_RDONLY);
    //新文件创建及权限设置0666
    fd_dest = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //读至文件末尾结束循环
    while((len = read(fd_src, buf, sizeof(buf)))>0){
        write(fd_dest, buf, len);
    }
    //关闭文件
    close(fd_src);
    close(fd_dest);

    return 0;
}

运行及结果:

yu@ubuntu:~/Linux/206$ ls
copy.c  src

yu@ubuntu:~/Linux/206$ cat src
hey, how are you today?

yu@ubuntu:~/Linux/206$ gcc -o copy copy.c 
yu@ubuntu:~/Linux/206$ ls
copy  copy.c  src

yu@ubuntu:~/Linux/206$ ./copy src dest

yu@ubuntu:~/Linux/206$ ls -l
total 20
-rwxrwxr-x 1 yu yu 7560 Feb  6 10:51 copy
-rw-rw-r-- 1 yu yu  487 Feb  6 10:50 copy.c
-rw-rw-r-- 1 yu yu   24 Feb  6 10:51 dest
-rw-rw-r-- 1 yu yu   24 Feb  6 10:41 src

yu@ubuntu:~/Linux/206$ cat dest 
hey, how are you today?

Linux文件复制cp命令的实现_第1张图片

你可能感兴趣的:(Linux,programming)