[c++] 파일 병합

아래는 파일 병합을 수행하는 간단한 C++ 예제 코드입니다.

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

int main() {
    std::ofstream mergedFile("merged.txt", std::ios_base::app);

    if (!mergedFile) {
        std::cerr << "파일을 열 수 없습니다." << std::endl;
        return 1;
    }

    std::string filename1 = "file1.txt";
    std::string filename2 = "file2.txt";
    std::ifstream file1(filename1);
    std::ifstream file2(filename2);

    if (!file1 || !file2) {
        std::cerr << "파일을 열 수 없습니다." << std::endl;
        return 1;
    }

    std::string line;

    while (std::getline(file1, line)) {
        mergedFile << line << std::endl;
    }

    while (std::getline(file2, line)) {
        mergedFile << line << std::endl;
    }

    std::cout << "파일이 성공적으로 병합되었습니다." << std::endl;

    file1.close();
    file2.close();
    mergedFile.close();

    return 0;
}

위의 예제 코드는 file1.txt와 file2.txt의 내용을 merged.txt로 병합하는 과정을 보여줍니다. ifstream를 사용하여 각 파일을 열고, 해당 파일에서 한 줄씩 읽어 ofstream을 사용하여 merged.txt에 쓰는 방식으로 병합합니다.

파일 병합에는 더 복잡한 여러 가정(CSV, JSON 등)을 다루는 경우도 있을 수 있으며, 이에 따라 병합 로직이 달라질 수 있습니다. 필요에 따라 적절히 코드를 변경하여 사용하시기 바랍니다.

이러한 파일 병합 기능을 구현할 때에는 예외 처리 및 파일이나 리소스를 안전하게 다루는 것이 중요합니다.