C++ Filesystem 개념 정리 | "파일시스템 라이브러리" 가이드

C++ Filesystem 개념 정리 | "파일시스템 라이브러리" 가이드

이 글의 핵심

std::filesystem(C++17)은 경로·디렉터리·파일 복사·삭제 등을 표준으로 다루는 라이브러리입니다. 이 글에서는 path, exists, create_directory, copy 등 기본 연산과 네임스페이스 사용법을 예제 중심으로 설명합니다.

filesystem이란?

표준 라이브러리만으로 경로 조합, 존재 확인, 디렉터리 생성·삭제를 하려면 filesystem의 설계를 갖추는 것이 좋습니다. 이 글에서는 네임스페이스 fspath 객체를 중심으로 실무에서 자주 쓰는 연산을 빠르게 훑을 수 있습니다.

파일시스템 조작 라이브러리 (C++17)

#include <filesystem>

namespace fs = std::filesystem;

fs::path p = "/home/user/file.txt";
bool exists = fs::exists(p);

기본 연산

#include <filesystem>

namespace fs = std::filesystem;

// 존재 확인
if (fs::exists("file.txt")) {}

// 디렉토리 생성
fs::create_directory("mydir");

// 파일 삭제
fs::remove("file.txt");

// 복사
fs::copy("src.txt", "dst.txt");

실전 예시

예시 1: 파일 정보

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

void printFileInfo(const fs::path& p) {
    if (!fs::exists(p)) {
        std::cout << "파일 없음" << std::endl;
        return;
    }
    
    std::cout << "경로: " << p << std::endl;
    std::cout << "크기: " << fs::file_size(p) << " bytes" << std::endl;
    
    if (fs::is_regular_file(p)) {
        std::cout << "일반 파일" << std::endl;
    } else if (fs::is_directory(p)) {
        std::cout << "디렉토리" << std::endl;
    }
}

예시 2: 디렉토리 순회

void listFiles(const fs::path& dir) {
    for (const auto& entry : fs::directory_iterator(dir)) {
        std::cout << entry.path() << std::endl;
    }
}

void listFilesRecursive(const fs::path& dir) {
    for (const auto& entry : fs::recursive_directory_iterator(dir)) {
        std::cout << entry.path() << std::endl;
    }
}

예시 3: 파일 복사

void backupFiles(const fs::path& src, const fs::path& dst) {
    if (!fs::exists(dst)) {
        fs::create_directories(dst);
    }
    
    for (const auto& entry : fs::directory_iterator(src)) {
        fs::path dstPath = dst / entry.path().filename();
        
        if (fs::is_regular_file(entry)) {
            fs::copy_file(entry.path(), dstPath, 
                          fs::copy_options::overwrite_existing);
        }
    }
}

예시 4: 임시 파일

#include <fstream>

void createTempFile() {
    fs::path tempDir = fs::temp_directory_path();
    fs::path tempFile = tempDir / "myapp_temp.txt";
    
    std::ofstream ofs(tempFile);
    ofs << "임시 데이터" << std::endl;
    ofs.close();
    
    // 사용 후 삭제
    fs::remove(tempFile);
}

경로 조작

fs::path p = "/home/user/file.txt";

p.filename();     // "file.txt"
p.extension();    // ".txt"
p.stem();         // "file"
p.parent_path();  // "/home/user"

// 경로 결합
fs::path dir = "/home/user";
fs::path file = dir / "file.txt";

자주 발생하는 문제

문제 1: 예외 처리

// ❌ 예외 무시
fs::remove("file.txt");  // 없으면 예외

// ✅ 예외 처리
try {
    fs::remove("file.txt");
} catch (const fs::filesystem_error& e) {
    std::cout << "에러: " << e.what() << std::endl;
}

// ✅ error_code 사용
std::error_code ec;
fs::remove("file.txt", ec);
if (ec) {
    std::cout << "에러: " << ec.message() << std::endl;
}

문제 2: 경로 구분자

// ❌ 플랫폼 의존
fs::path p = "dir\\file.txt";  // Windows만

// ✅ 플랫폼 독립
fs::path p = "dir" / "file.txt";

문제 3: 상대 경로

fs::path rel = "file.txt";
fs::path abs = fs::absolute(rel);

std::cout << "상대: " << rel << std::endl;
std::cout << "절대: " << abs << std::endl;

문제 4: 디렉토리 삭제

// ❌ 비어있지 않으면 실패
fs::remove("dir");

// ✅ 재귀 삭제
fs::remove_all("dir");

파일 타입 확인

fs::path p = "file.txt";

if (fs::is_regular_file(p)) {
    std::cout << "일반 파일" << std::endl;
}

if (fs::is_directory(p)) {
    std::cout << "디렉토리" << std::endl;
}

if (fs::is_symlink(p)) {
    std::cout << "심볼릭 링크" << std::endl;
}

FAQ

Q1: filesystem은?

A: C++17. 파일시스템 조작.

Q2: 플랫폼 독립?

A: 네. Windows/Linux/macOS 지원.

Q3: 예외 처리?

A:

  • try-catch
  • error_code 오버로드

Q4: 성능?

A: 시스템 콜 사용. 적절히 사용.

Q5: 경로 구분자?

A: / 연산자로 플랫폼 독립.

Q6: filesystem 학습 리소스는?

A:

  • “C++17 The Complete Guide”
  • “C++ Primer”
  • cppreference.com

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ Filesystem | “파일시스템” C++17 라이브러리 가이드
  • C++ File Operations | “파일 연산” 가이드
  • C++ path | “경로 처리” 가이드

관련 글

  • C++ Directory Iterator |
  • C++ File Operations |
  • C++ File Status |
  • C++ Filesystem 빠른 참조 |
  • C++ path |