C++ copyfile怎樣復(fù)制大文件

c++
小樊
81
2024-10-16 19:30:17

在C++中,復(fù)制大文件時(shí)通常使用流式復(fù)制,這樣可以避免一次性將整個(gè)文件加載到內(nèi)存中。以下是一個(gè)使用C++標(biāo)準(zhǔn)庫(kù)中的std::ifstreamstd::ofstream進(jìn)行大文件復(fù)制的示例:

#include <iostream>
#include <fstream>
#include <string>

bool copyFile(const std::string& sourcePath, const std::string& destinationPath) {
    std::ifstream sourceFile(sourcePath, std::ios::binary);
    if (!sourceFile) {
        std::cerr << "Error opening source file: " << sourcePath << std::endl;
        return false;
    }

    std::ofstream destinationFile(destinationPath, std::ios::binary);
    if (!destinationFile) {
        std::cerr << "Error opening destination file: " << destinationPath << std::endl;
        return false;
    }

    // Copy data from source to destination
    destinationFile << sourceFile.rdbuf();

    // Check if the copy was successful
    if (!sourceFile.eof()) {
        std::cerr << "Error copying file: " << sourcePath << std::endl;
        return false;
    }

    // Close files
    sourceFile.close();
    destinationFile.close();

    return true;
}

int main() {
    std::string sourcePath = "path/to/source/file.txt";
    std::string destinationPath = "path/to/destination/file.txt";

    if (copyFile(sourcePath, destinationPath)) {
        std::cout << "File copied successfully!" << std::endl;
    } else {
        std::cerr << "File copy failed!" << std::endl;
    }

    return 0;
}

在這個(gè)示例中,copyFile函數(shù)接受源文件路徑和目標(biāo)文件路徑作為參數(shù)。它首先打開這兩個(gè)文件,然后使用rdbuf()函數(shù)獲取源文件的緩沖區(qū),并將其直接寫入目標(biāo)文件。這樣可以確保整個(gè)文件被逐塊復(fù)制,而不是一次性加載到內(nèi)存中。最后,函數(shù)關(guān)閉文件并返回操作是否成功。

請(qǐng)注意,這個(gè)示例假設(shè)源文件和目標(biāo)文件都是二進(jìn)制文件。如果需要復(fù)制文本文件,可能需要對(duì)字符進(jìn)行適當(dāng)?shù)霓D(zhuǎn)換。

0