如何使用C++ copyfile跨平臺(tái)操作

c++
小樊
81
2024-10-16 19:31:18

copyfile函數(shù)在Windows和Unix-like系統(tǒng)中都有對(duì)應(yīng)的實(shí)現(xiàn),但它們的函數(shù)簽名和參數(shù)有所不同。為了實(shí)現(xiàn)跨平臺(tái)操作,你可以使用條件編譯來處理不同系統(tǒng)上的差異。以下是一個(gè)使用C++ copyfile跨平臺(tái)操作的示例:

#include <iostream>
#include <fstream>
#include <filesystem> // C++17中的文件系統(tǒng)庫(kù)

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#endif

bool copyfile(const std::string& src, const std::string& dest) {
    // 使用C++17文件系統(tǒng)庫(kù)進(jìn)行跨平臺(tái)操作
    std::filesystem::path src_path(src);
    std::filesystem::path dest_path(dest);

    try {
        if (std::filesystem::exists(src_path)) {
            if (std::filesystem::is_regular_file(src_path)) {
                std::filesystem::copy(src_path, dest_path, std::filesystem::copy_options::overwrite_existing);
                return true;
            } else {
                std::cerr << "Source is not a regular file." << std::endl;
                return false;
            }
        } else {
            std::cerr << "Source file does not exist." << std::endl;
            return false;
        }
    } catch (const std::filesystem::filesystem_error& e) {
        std::cerr << "Filesystem error: " << e.what() << std::endl;
        return false;
    }
}

int main() {
    std::string src = "source.txt";
    std::string dest = "destination.txt";

    if (copyfile(src, dest)) {
        std::cout << "File copied successfully." << std::endl;
    } else {
        std::cout << "Failed to copy file." << std::endl;
    }

    return 0;
}

這個(gè)示例使用了C++17中的文件系統(tǒng)庫(kù)(<filesystem>),它提供了一個(gè)跨平臺(tái)的文件系統(tǒng)操作接口。copyfile函數(shù)首先檢查源文件是否存在,然后使用std::filesystem::copy函數(shù)進(jìn)行復(fù)制。注意,這個(gè)示例僅適用于C++17及更高版本。如果你的編譯器不支持C++17,你需要尋找其他方法實(shí)現(xiàn)跨平臺(tái)文件復(fù)制。

0