• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C语言自己实现linux下cp文件复制命令

OC/C/C++ 水墨上仙 2646次浏览

C语言自己实现linux下cp文件复制命令

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
    char *buf = NULL;
    int fd_src = -1;
    int fd_dest = -1;
    int buf_size = 4096;
    int cnt = 0;
    struct flock lock;

    if (argc < 3) {
        printf("usage: %s <src_file> <dest_file> [buf_size]\n", argv[0]);
        return 0;
    }

    if ((fd_src=open(argv[1], O_RDONLY)) == -1) {
        perror("open src. file");
        return 1;
    }
    if ((fd_dest=open(argv[2], O_WRONLY|O_CREAT|O_EXCL, 0664)) == -1) {
        perror("open dest. file");
        close(fd_src);
        return 2;
    }
    if (argc == 4) {
        buf_size = atoi(argv[3]);
    }
    buf = sbrk(buf_size);
    if ((void*)-1 == buf) {
        perror("malloc");
        close(fd_src);
        close(fd_dest);
        return 3;
    }

    lock.l_type = F_RDLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;
    lock.l_pid = -1;
    if (fcntl(fd_src, F_SETLK, &lock) == -1) {
        fprintf(stderr, "%s has been locked by other process\n", argv[1]);
        close(fd_src);
        close(fd_dest);
        return 8;
    }

    errno = 0;
    while ((cnt = read(fd_src, buf, buf_size)) > 0) {
        if (write(fd_dest, buf, cnt) < cnt) {
            perror("write");
            close(fd_src);
            close(fd_dest);
            return 4;
        }
    }
    if (0 != errno) {
        perror("read");
    }
    close(fd_src);
    fd_src = -1;
    close(fd_dest);
    fd_dest = -1;
    brk(buf);

    return 0;
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C语言自己实现linux下cp文件复制命令
喜欢 (0)
加载中……