cp 自写 linux 命令

cp 1.log 2.log

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

#define BUFSIZE 512

int main(int argc, char**argv) {
    int fd_in, fd_out;
    int nread;
    char buf[BUFSIZE];
    if (argc != 3) {
        printf("Usage: %s sourcefile destfile\n", argv[0]);
        exit(1);
    }
    if ((fd_in = open(argv[1], O_RDONLY)) == -1) {
        perror(argv[1]);
        exit(1);
    }
    if ((fd_out = creat(argv[2], 0644)) == -1) {
        perror(argv[2]);
        exit(1);
    }
    while ((nread = read(fd_in, buf, sizeof(buf))) > 0) {
        int nwrite;
        if ((nwrite = write(fd_out, buf, nread)) != nread) {
            perror("write");
            exit(1);
        }
        memset(buf, 0, BUFSIZE + 5);
    }
    close(fd_in);
    close(fd_out);
    return 0;
}

发布了209 篇原创文章 · 获赞 72 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43870649/article/details/105031719