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;
}
网友评论