编写程序实现拷贝文件功能

该程序运行时有两个参数,分别为源文件和目标文件,程序能够显示打开、读取、写入、关闭文件操作时的错误。

假定编译后的程序名为mycopy,使用方法如下:

./mycopy src.txt dest.txt

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

#define BUFFER_SIZE 1024      //每次读写缓存大小,影响运行效率

int main(int argc, char *argv[])
{
        int src_fd, dest_fd;
        unsigned char buff[BUFFER_SIZE];
        int real_read_size;

        if(argc!=3) //命令要跟两个参数
        {
                printf("usage: ./mycopy <src file> <dest file>\n");
                exit(EXIT_FAILURE);
        }

        src_fd = open(argv[1], O_RDONLY); //只读打开第1个参数代表的源文件
        if(src_fd==-1)
        {
                perror("open src file error: ");
                exit(EXIT_FAILURE);
        }

        dest_fd = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0777); //读写打开第2个参数代表的目标文件
        if(dest_fd==-1)
        {
                perror("open dest file error: ");
                exit(EXIT_FAILURE);
        }

        while( (real_read_size=read(src_fd, buff, BUFFER_SIZE))>0  )
        {
                write(dest_fd, buff, real_read_size);
        }

        close(src_fd);
        close(dest_fd);
        printf("copy %s to %s successfully.\n", argv[1], argv[2]);
        exit(EXIT_SUCCESS);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值