Linux编程

编写cp命令

2018-01-20  本文已影响0人  wangdsh

cp命令能够复制文件,典型的用法是:
$ cp source-file target-file

编写cp命令用到的系统调用:
open、creat(创建/重写文件)、close

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

int main(int ac,  char *av[]) {
    int buf_size = 1024;
    int n_chars;
    char buf[buf_size];
    if (ac != 3) {
        printf("Invalid argument. Usage: source destination.\n");
        exit(1);
    }   
    int fd_in = open(av[1], O_RDONLY);
    if (fd_in == -1) {
        printf("Can not open %s\n", av[1]);
        exit(1);
    }   
    int fd_out = creat(av[2], 0644);
    if (fd_out == -1) {
        printf("Can not open or create %s\n", av[2]);
        exit(1);
    }   
    while((n_chars = read(fd_in, buf, buf_size)) > 0) {
        if (write(fd_out, buf, n_chars) != n_chars) {
            printf("wirte error to %s\n", av[2]);
        }   
    }   
    close(fd_in);
    close(fd_out);
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读