利用C++ truncate实现文件备份的技巧

1949idc 2年前 (2024-09-19) 阅读数 302 #编程语言

在C++中,你可以使用truncate()函数来实现文件备份

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

bool backupFile(const std::string &src, const std::string &dst) {
    int src_fd = open(src.c_str(), O_RDONLY);
    if (src_fd == -1) {
        std::cerr << "Error opening source file: "<< strerror(errno)<< std::endl;
        return false;
    }

    int dst_fd = open(dst.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (dst_fd == -1) {
        std::cerr << "Error opening destination file: "<< strerror(errno)<< std::endl;
        close(src_fd);
        return false;
    }

    struct stat st;
    fstat(src_fd, &st);
    off_t size = st.st_size;

    sendfile(dst_fd, src_fd, nullptr, size);

    close(src_fd);
    close(dst_fd);

    return true;
}

int main() {
    std::string src_file = "source.txt";
    std::string dst_file = "backup.txt";

    if (backupFile(src_file, dst_file)) {
        std::cout << "File backup successful!"<< std::endl;
    } else {
        std::cerr << "File backup failed."<< std::endl;
    }

    return 0;
}

这个示例中的backupFile()函数接受两个参数:源文件路径(src)和目标文件路径(dst)。函数首先打开源文件并获取其文件描述符(src_fd),然后创建或打开目标文件并获取其文件描述符(dst_fd)。接下来,使用sendfile()函数将源文件的内容复制到目标文件。最后,关闭源文件和目标文件的文件描述符。

main()函数中,我们调用backupFile()函数来备份一个名为source.txt的文件到一个名为backup.txt的文件。如果备份成功,程序将输出"File backup successful!“,否则输出"File backup failed.”。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业