#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;
}