IO(day04)

创建子父进程,子进程将1.txt内容拷贝到2.txt中,父进程将3.txt内容拷贝到4.txt中。

#include<myhead.h>
// 定义文件拷贝函数
void copy_file(const char *txt_1, const char *txt_2) {
    int fd, fd1;
    char buff[1024];
    int len;

    // 打开源文件
    fd = open("1.txt", O_RDONLY);
    if (fd == -1) {
        perror("打开源文件失败");
    }

    // 打开目标文件
    fd1 = open("2.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd1 == -1) {
        perror("打开目标文件失败");
        close(fd);
    }

    // 拷贝文件内容
    while ((len= read(fd, buff, sizeof(buff))) > 0) {
        if (write(fd1, buff, len) != len) {
            perror("写入目标文件失败");
            close(fd);
            close(fd1);
        }
    }

    // 关闭文件描述符
    close(fd);
    close(fd1);
}

int main() {
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork 失败");
        return -1;
    } else if (pid == 0) {
        copy_file("1.txt", "2.txt");
        printf("子进程完成文件拷贝\n");
    } else {
        copy_file("3.txt", "4.txt");
        printf("父进程完成文件拷贝\n");
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值