copy() 复制

//实现一个简单的cp()命令,将源文件的内容复制到新文件中,程序的第一个参数代表已存在的源文件,第二个参数代表新文件
// ./copy test test.txt
#include <sys/stat.h>
#include <fcntl.h>
#include "tlpi_hdr.h"

#define EXIT_SUCESS 0
#ifndef BUF_SIZE    /*Allow "cc -D" to override definition*/
#define BUF_SIZE 1024
#endif

int
main(int argc,char *argv[])
{
    int intputFd,outputFd,openFlags;
    mode_t filePerms;
    ssize_t numRead;
    char buf[BUF_SIZE];

    if (argc != 3 || strcmp(argv[1],"--help") == 0)
        usageErr("%s old-file new-file\n",argv[0]);

    /*Open input and output files*/

    intputFd = open(argv[1],O_RDONLY);
    if (intputFd == -1)
        errExit("opening file %s",argv[1]);

    openFlags = O_CREAT | O_WRONLY | O_TRUNC;
    filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;  /*rw-rw-rw*/
    outputFd = open(argv[2],openFlags,filePerms);
    if (outputFd == -1)
        errExit("opening file %s",argv[2]);

    /*Transfer data until we encounter end of input or an error*/
    while ((numRead = read(intputFd,buf,BUF_SIZE)) > 0)
        if (write(outputFd,buf,numRead) != numRead)
            fatal("couldn't write whole buffer");
    if (numRead == -1)
        errExit("read");

    if (close(intputFd) == -1)
        errExit("close input");
    if (close(outputFd) == -1)
        errExit("close output");

    exit(EXIT_SUCESS);
}

/*
使用示例:
[root@localhost linux-test]# vi copy.c
[root@localhost linux-test]# gl++ copy.c
[root@localhost linux-test]# ls
a.out  copy.c  tlpi
[root@localhost linux-test]# echo "hello world" > a.txt
[root@localhost linux-test]# echo > b.txt
[root@localhost linux-test]# cat b.txt
[root@localhost linux-test]# ./a.out a.txt b.txt
[root@localhost linux-test]# cat b.txt
hello world
 */
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值