linux系统下实现文件复制

本文深入讲解了在Linux系统下如何使用C语言实现文件复制。通过分析源代码,详细解释了open、read、write和close等系统调用的功能及用法,并提供了一个完整的文件复制程序示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

linux系统下实现文件复制:

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

void copy(char *from, char *to){
    int fromFd = -1, toFd = -1;
    ssize_t nread;
    char buf[BUFSIZE];
    if ((fromFd = open(from, O_RDONLY)) == -1){
        perror("open");
        exit(1);
    }
    if ((toFd = open(to, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) == -1){
        perror("open to");
        exit(1);
    }

    nread = read(fromFd, buf, sizeof(buf));//从frmoFd中读sizeof(buf)个字节到buf

    while (nread > 0){
        if (write(toFd, buf, nread) != nread){
            printf("write %s error\n", to);//一般不会出错
        }
        nread = read(fromFd, buf, sizeof(buf));
    }//nread == 0 则代表读完
    if (nread == -1){
        printf("write %s error\n", to);
    }
    close(fromFd);
    close(toFd);
}

int main(int argc, char **argv){
    if (argc != 3){
        printf("Usage : program fromFileName toFileName\n");
        exit(1);
    }
    copy(argv[1], argv[2]);//argcv[]对应从命令行输入的命令
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值