在linux环境下用读写函数写一个文件复制的程序

在linux环境下用读写函数写一个文件复制的程序
在下面程序的基础上如何修改 写一个文件复制的程序

img

img


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

#define BUFFER_SIZE 4096

int main() {
    const char* sourceFile = "source.txt";
    const char* destFile = "destination.txt";

    // 打开源文件和目标文件
    int sourceFd = open(sourceFile, O_RDONLY);
    if (sourceFd == -1) {
        std::cerr << "无法打开源文件" << std::endl;
        return 1;
    }

    int destFd = open(destFile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if (destFd == -1) {
        std::cerr << "无法创建目标文件" << std::endl;
        close(sourceFd);
        return 1;
    }

    // 读取源文件内容,并将内容写入目标文件
    char buffer[BUFFER_SIZE];
    ssize_t bytesRead, bytesWritten;
    while ((bytesRead = read(sourceFd, buffer, BUFFER_SIZE)) > 0) {
        bytesWritten = write(destFd, buffer, bytesRead);
        if (bytesWritten != bytesRead) {
            std::cerr << "写入目标文件时发生错误" << std::endl;
            close(sourceFd);
            close(destFd);
            return 1;
        }
    }

    // 关闭文件描述符
    close(sourceFd);
    close(destFd);

    std::cout << "文件复制完成" << std::endl;

    return 0;
}