C++현대 C++

파일 시스템 기본

C++17 `std::filesystem`으로 경로 다루기, 파일/디렉토리 조작, 존재 여부 확인, 디렉토리 순회까지 정리합니다.

마지막 수정 2026년 3월 26일

기본 패턴

cpp
#include <filesystem>
namespace fs = std::filesystem;

fs::path p{"data/config.json"};

if (fs::exists(p)) {
    std::cout << "크기: " << fs::file_size(p) << " bytes\n";
}

설명

path — 경로 표현

cpp
fs::path p1{"data/config.json"};
fs::path p2 = fs::current_path() / "logs" / "app.log";  // / 연산자로 조합

std::cout << p2.filename();     // "app.log"
std::cout << p2.stem();         // "app"
std::cout << p2.extension();    // ".log"
std::cout << p2.parent_path();  // ".../logs"

// 플랫폼 간 이식성 — 슬래시 방향을 OS에 맞게 자동 변환

존재 확인과 파일 정보

cpp
fs::path p{"readme.txt"};

fs::exists(p);                  // 존재 여부
fs::is_regular_file(p);         // 일반 파일인가
fs::is_directory(p);            // 디렉토리인가
fs::file_size(p);               // 파일 크기 (bytes)
fs::last_write_time(p);         // 마지막 수정 시각

// status로 한 번에 여러 정보
auto st = fs::status(p);
if (st.type() == fs::file_type::regular) { /* ... */ }

디렉토리 생성 / 삭제 / 복사

cpp
// 생성
fs::create_directory("output");
fs::create_directories("a/b/c");    // 중간 경로도 함께 생성

// 삭제
fs::remove("output/temp.txt");       // 파일 하나
fs::remove_all("output");            // 디렉토리 전체 (비어 있지 않아도)

// 복사
fs::copy_file("src.txt", "dst.txt");
fs::copy("src_dir", "dst_dir", fs::copy_options::recursive);

// 이름 변경 / 이동
fs::rename("old.txt", "new.txt");

디렉토리 순회

cpp
// 단순 순회 (하위 디렉토리 미진입)
for (const auto& entry : fs::directory_iterator{"."}) {
    std::cout << entry.path() << "\n";
}

// 재귀 순회 (하위 디렉토리 포함)
for (const auto& entry : fs::recursive_directory_iterator{"."}) {
    if (entry.is_regular_file()) {
        std::cout << entry.path().filename()
                  << " (" << entry.file_size() << " bytes)\n";
    }
}

// 특정 확장자만 필터
for (const auto& entry : fs::directory_iterator{"."}) {
    if (entry.path().extension() == ".cpp") {
        std::cout << entry.path() << "\n";
    }
}

오류 처리

cpp
// 예외 방식 (기본)
try {
    fs::file_size("not_exist.txt");
} catch (const fs::filesystem_error& e) {
    std::cerr << e.what() << "\n";
}

// 오류 코드 방식 (예외 없이)
std::error_code ec;
auto size = fs::file_size("not_exist.txt", ec);
if (ec) {
    std::cerr << "오류: " << ec.message() << "\n";
}

빠른 정리

함수역할
fs::path경로 표현, / 연산자로 조합
fs::exists경로 존재 여부
fs::is_regular_file / is_directory파일/디렉토리 구분
fs::file_size파일 크기 (bytes)
fs::create_directories중간 경로 포함 생성
fs::remove_all디렉토리 통째로 삭제
fs::copy_file / fs::copy파일/디렉토리 복사
fs::rename이름 변경 또는 이동
directory_iterator디렉토리 내 항목 순회
recursive_directory_iterator하위 포함 전체 순회

주의할 점

std::filesystem은 C++17 이상에서 사용 가능합니다. 컴파일 옵션에 -std=c++17(GCC/Clang) 또는 /std:c++17(MSVC)을 확인하세요.

Linux에서 GCC를 사용할 경우 일부 버전에서 링크 옵션 -lstdc++fs가 필요합니다 (GCC 9 이전).

remove_all은 되돌릴 수 없습니다. 프로덕션 코드에서는 경로를 충분히 검증한 뒤 호출하세요.

참고 링크

1 sources