[c++] 파일 및 디렉토리 병합하기
파일과 디렉토리 병합하기
파일과 디렉토리를 병합하는 프로그램을 작성하기 위해서는 파일 및 디렉토리의 구조를 조작해야 합니다. C++에서는 파일 및 디렉토리 조작을 위해 <iostream>
, <fstream>
, <filesystem>
등의 라이브러리를 사용할 수 있습니다.
파일 병합
다음은 C++을 사용하여 두 개 이상의 파일을 병합하는 예제 코드입니다.
#include <iostream>
#include <fstream>
int main() {
std::ifstream file1("file1.txt");
std::ifstream file2("file2.txt");
std::ofstream outfile("combined_file.txt");
outfile << file1.rdbuf();
outfile << file2.rdbuf();
file1.close();
file2.close();
outfile.close();
return 0;
}
위 코드는 file1.txt
와 file2.txt
의 내용을 읽어 combined_file.txt
에 순차적으로 병합합니다.
디렉토리 병합
디렉토리를 병합하기 위해서는 <filesystem>
라이브러리를 사용할 수 있습니다. 아래 예제 코드는 모든 파일과 디렉토리를 대상 디렉토리로 복사하는 방법을 보여줍니다.
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void copy_directory(const fs::path &source, const fs::path &destination) {
fs::create_directories(destination);
for (const auto &entry : fs::recursive_directory_iterator(source)) {
const auto relative_path = entry.path().lexically_relative(source);
const auto target = destination / relative_path;
if (fs::is_directory(entry.status())) {
fs::create_directories(target);
} else if (fs::is_regular_file(entry.status())) {
fs::copy_file(entry, target, fs::copy_options::overwrite_existing);
}
}
}
int main() {
fs::path source_dir = "source_directory";
fs::path destination_dir = "destination_directory";
copy_directory(source_dir, destination_dir);
return 0;
}
위 코드는 source_directory
의 모든 파일 및 디렉토리를 destination_directory
로 복사합니다.
이제 파일 및 디렉토리를 병합하는 프로그램을 작성하는 데 필요한 기본적인 지식을 습득했습니다. 원하는 결과를 얻기 위해 파일 및 디렉토리 조작에 대해 더 자세히 알아보시길 권장합니다.