[c++] 파일 및 디렉토리 압축 해제하기

파일 및 디렉토리 압축 해제하기

압축 파일을 해제하는 데 사용할 수 있는 라이브러리로는 zlib 및 libarchive 등이 있습니다. 이를 사용하여 C++로 파일 및 디렉토리를 압축 해제할 수 있습니다.

파일 압축 해제하기

#include <iostream>
#include <fstream>
#include <zlib.h>

int main() {
    // 압축 해제할 파일명
    const char *input_file = "compressed_file.gz";
    // 압축 해제한 결과를 저장할 파일명
    const char *output_file = "decompressed_file.txt";

    gzFile file = gzopen(input_file, "rb");
    if (!file) {
        std::cerr << "압축 파일을 열 수 없습니다." << std::endl;
        return -1;
    }

    std::ofstream out(output_file, std::ios::binary);
    char buffer[128];
    int num_read = 0;
    while ((num_read = gzread(file, buffer, sizeof(buffer))) > 0) {
        out.write(buffer, num_read);
    }
    gzclose(file);
    return 0;
}

디렉토리 압축 해제하기

#include <iostream>
#include <archive.h>
#include <archive_entry.h>

int main() {
    // 압축 해제할 파일명
    const char *input_file = "compressed_directory.tar.gz";
    // 압축 해제한 결과를 저장할 디렉토리명
    const char *output_directory = "decompressed_directory";

    struct archive *a = archive_read_new();
    archive_read_support_filter_all(a);
    archive_read_support_format_all(a);

    struct archive *ext = archive_write_disk_new();
    archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
    archive_write_disk_set_standard_lookup(ext);

    if (archive_read_open_filename(a, input_file, 10240) != ARCHIVE_OK) {
        return -1;
    }

    struct archive_entry *entry;
    while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
        archive_read_extract(a, entry, ext);
    }
    archive_read_free(a);
    archive_write_free(ext);
    return 0;
}

위 코드는 C++에서 파일 및 디렉토리를 압축 해제하는 간단한 예제입니다. 바이너리 파일을 처리하기 때문에 적절한 예외 처리 및 에러 핸들링이 필요합니다.

더 자세한 내용은 zlib 및 libarchive 라이브러리의 공식 문서를 참조하시기 바랍니다.

[참고 자료]