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

   2024-09-30 2360
核心提示:在C++中,你可以使用truncate()函数来实现文件备份#includeiostream#include fstream#include cstring#include fcntl.h#include

在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.”。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号