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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章