C++ copyfile在復(fù)制時(shí)如何控制進(jìn)度

c++
小樊
82
2024-10-16 19:36:18

在C++中,你可以使用標(biāo)準(zhǔn)庫(kù)中的文件流(如 ifstreamofstream)和系統(tǒng)相關(guān)的API來(lái)實(shí)現(xiàn)文件復(fù)制,并通過(guò)計(jì)算已復(fù)制的字節(jié)數(shù)來(lái)控制進(jìn)度。以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用C++復(fù)制文件并顯示進(jìn)度:

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

void copyFile(const std::string& source, const std::string& destination) {
    std::ifstream src(source, std::ios::binary);
    if (!src) {
        std::cerr << "Error opening source file: " << source << std::endl;
        return;
    }

    std::ofstream dest(destination, std::ios::binary);
    if (!dest) {
        std::cerr << "Error opening destination file: " << destination << std::endl;
        src.close();
        return;
    }

    const size_t bufferSize = 1024 * 1024; // 1 MB
    char buffer[bufferSize];
    size_t totalBytesRead = 0;
    size_t bytesRead;

    while ((bytesRead = src.read(buffer, bufferSize)) > 0) {
        dest.write(buffer, bytesRead);
        totalBytesRead += bytesRead;

        // 計(jì)算進(jìn)度百分比
        double progress = static_cast<double>(totalBytesRead) / src.tellg() * 100;
        std::cout << "Progress: " << progress << "%\r" << std::flush;
    }

    if (src.eof()) {
        std::cout << std::endl;
    } else {
        std::cerr << "Error reading source file: " << source << std::endl;
    }

    src.close();
    dest.close();
}

int main() {
    std::string sourceFile = "source.txt";
    std::string destinationFile = "destination.txt";

    copyFile(sourceFile, destinationFile);

    return 0;
}

在這個(gè)示例中,copyFile函數(shù)接受源文件名和目標(biāo)文件名作為參數(shù)。它使用ifstream打開源文件,并使用ofstream打開目標(biāo)文件。然后,它在一個(gè)循環(huán)中讀取源文件的內(nèi)容,并將其寫入目標(biāo)文件。在每次迭代中,它計(jì)算已復(fù)制的字節(jié)數(shù)占總字節(jié)數(shù)的百分比,并輸出進(jìn)度。

請(qǐng)注意,這個(gè)示例僅適用于支持C++11或更高版本的編譯器。如果你使用的是較舊的編譯器,你可能需要調(diào)整代碼以適應(yīng)其限制。

0