编写cp命令

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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,323评论 19 139
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 14,182评论 2 33
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,713评论 0 17
  • 当夕阳洒下第一抹动人的黄昏,我坐在这片花田的田埂上,沉醉于那落日映在天边的绯红…… 风儿携着片片飘散的花瓣,飞舞在...
    下流书生阅读 3,517评论 0 2
  • 俞桂飘香琴书韵,潜畅清风玉满堂 纵浪大化里 不喜亦不惧 应尽便须尽 无复独多虑
    一条逐流的鱼阅读 825评论 1 1