cpp 文件转录

#include
#include
#include
#include
#include
#include

namespace fs = std::filesystem;

class FileAggregator {
public:
// 将指定目录下的所有文件内容合并到一个文件中
void mergeFiles(const std::string& dirPath, const std::string& outputFilePath) {
std::ofstream outputFile(outputFilePath);
if (!outputFile.is_open()) {
std::cerr << "Error opening output file: " << outputFilePath << std::endl;
return;
}

    for (const auto& entry : fs::recursive_directory_iterator(dirPath)) {
        if (fs::is_regular_file(entry)) {
            std::string relativePath = fs::relative(entry.path(), dirPath).string();
            outputFile << relativePath << std::endl;

            std::ifstream inputFile(entry.path());
            if (inputFile.is_open()) {
                outputFile << inputFile.rdbuf();
            } else {
                std::cerr << "Error opening input file: " << entry.path() << std::endl;
            }
            outputFile << std::endl;
        }
    }

    outputFile.close();
}

// 从合并文件中重建目录结构和文件
void restoreFiles(const std::string& mergedFilePath, const std::string& outputDirPath) {
    std::ifstream mergedFile(mergedFilePath);
    if (!mergedFile.is_open()) {
        std::cerr << "Error opening merged file: " << mergedFilePath << std::endl;
        return;
    }

    std::string line;
    std::string currentFilePath;
    std::ofstream currentOutputFile;

    while (std::getline(mergedFile, line)) {
        if (currentOutputFile.is_open()) {
            if (line.empty()) {
                currentOutputFile.close();
            } else {
                currentOutputFile << line << std::endl;
            }
        } else {
            currentFilePath = outputDirPath + "/" + line;
            fs::create_directories(fs::path(currentFilePath).parent_path());
            currentOutputFile.open(currentFilePath);
            if (!currentOutputFile.is_open()) {
                std::cerr << "Error creating output file: " << currentFilePath << std::endl;
            }
        }
    }

    if (currentOutputFile.is_open()) {
        currentOutputFile.close();
    }

    mergedFile.close();
}

};

int main() {
FileAggregator aggregator;

// 合并文件
std::string dirPath = R"(D:\hard\untitled7\test1)";
std::string mergedFilePath = R"(D:\hard\untitled7\test2\merged_file.txt)";
aggregator.mergeFiles(dirPath, mergedFilePath);

// 重建文件
std::string outputDirPath = R"(D:\hard\untitled7\test4)";
aggregator.restoreFiles(mergedFilePath, outputDirPath);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值