본문으로 건너뛰기
Previous
Next
C++ File Operations | '파일 연산' 가이드

C++ File Operations | '파일 연산' 가이드

C++ File Operations | '파일 연산' 가이드

이 글의 핵심

C++ File Operations: "파일 연산" 가이드. 파일 연산 기본·디렉토리 연산.

들어가며

C++17 <filesystem> 라이브러리는 파일과 디렉토리 조작을 위한 표준 API를 제공합니다. 이전의 플랫폼별 API(POSIX, Windows API)를 대체하여 이식성 높은 코드를 작성할 수 있습니다.


실전 경험에서 배운 교훈

이 기술을 실무 프로젝트에 처음 도입했을 때, 공식 문서만으로는 알 수 없었던 많은 함정들이 있었습니다. 특히 프로덕션 환경에서 발생하는 엣지 케이스들은 로컬 개발 환경에서는 재현조차 되지 않았죠.

가장 어려웠던 점은 성능 최적화였습니다. 처음엔 “동작만 하면 되겠지”라고 생각했지만, 실제 사용자 트래픽이 몰리면서 병목 지점들이 하나씩 드러났습니다. 특히 데이터베이스 쿼리 최적화, 캐싱 전략, 에러 핸들링 구조 등은 여러 번의 장애를 겪으면서 개선해 나갔습니다.

이 글에서는 그런 시행착오를 통해 얻은 실전 노하우와, “이렇게 하면 안 된다”는 교훈들을 함께 정리했습니다. 특히 트러블슈팅 섹션은 실제 장애 대응 경험을 바탕으로 작성했으니, 비슷한 문제를 마주했을 때 참고하시면 도움이 될 것입니다.

1. 파일 연산 기본

기본 설정

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // 파일 존재 확인
    if (fs::exists("test.txt")) {
        std::cout << "파일 존재" << std::endl;
    }
    
    // 파일 크기
    auto size = fs::file_size("test.txt");
    std::cout << "크기: " << size << " bytes" << std::endl;
    
    return 0;
}

파일 복사

C/C++ 예제 코드입니다.

// 기본 복사
fs::copy_file("src.txt", "dst.txt");

// 덮어쓰기
fs::copy_file("src.txt", "dst.txt", 
              fs::copy_options::overwrite_existing);

// 디렉토리 복사 (재귀)
fs::copy("src_dir", "dst_dir", 
         fs::copy_options::recursive);

파일 이동 및 삭제

C/C++ 예제 코드입니다.

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

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

// 디렉토리 삭제 (재귀)
fs::remove_all("dir");

2. 디렉토리 연산

디렉토리 생성

// 단일 디렉토리
fs::create_directory("mydir");

// 중첩 디렉토리 (재귀)
fs::create_directories("path/to/dir");

// 이미 존재하면 false 반환
bool created = fs::create_directory("existing_dir");
if (!created) {
    std::cout << "이미 존재하거나 생성 실패" << std::endl;
}

디렉토리 순회

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // 현재 디렉토리 순회
    for (const auto& entry : fs::directory_iterator(".")) {
        std::cout << entry.path() << std::endl;
    }
    
    // 재귀 순회
    for (const auto& entry : fs::recursive_directory_iterator(".")) {
        if (entry.is_regular_file()) {
            std::cout << "파일: " << entry.path() << std::endl;
        } else if (entry.is_directory()) {
            std::cout << "디렉토리: " << entry.path() << std::endl;
        }
    }
    
    return 0;
}

3. 복사 옵션

copy_options 플래그

#include <filesystem>

namespace fs = std::filesystem;

// 기본: 이미 존재하면 에러
fs::copy_file("src.txt", "dst.txt");

// 덮어쓰기
fs::copy_file("src.txt", "dst.txt",
              fs::copy_options::overwrite_existing);

// 건너뛰기 (이미 존재하면 무시)
fs::copy_file("src.txt", "dst.txt",
              fs::copy_options::skip_existing);

// 업데이트 (더 최신이면 복사)
fs::copy_file("src.txt", "dst.txt",
              fs::copy_options::update_existing);

// 재귀 복사 (디렉토리)
fs::copy("src_dir", "dst_dir",
         fs::copy_options::recursive);

// 심볼릭 링크 복사 (링크 자체)
fs::copy("link", "new_link",
         fs::copy_options::copy_symlinks);

copy_options 조합:

// 재귀 + 덮어쓰기
fs::copy("src_dir", "dst_dir",
         fs::copy_options::recursive | 
         fs::copy_options::overwrite_existing);

4. 실전 예제

예제 1: 안전한 파일 복사

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

bool copyFileSafe(const fs::path& src, const fs::path& dst) {
    try {
        // 원본 파일 존재 확인
        if (!fs::exists(src)) {
            std::cerr << "원본 파일이 존재하지 않습니다: " << src << std::endl;
            return false;
        }
        
        // 대상 디렉토리 생성
        fs::create_directories(dst.parent_path());
        
        // 파일 복사
        fs::copy_file(src, dst, 
                      fs::copy_options::overwrite_existing);
        
        std::cout << "복사 완료: " << src << " -> " << dst << std::endl;
        return true;
        
    } catch (const fs::filesystem_error& e) {
        std::cerr << "에러: " << e.what() << std::endl;
        return false;
    }
}

int main() {
    copyFileSafe("data/input.txt", "backup/input.txt");
    return 0;
}

예제 2: 디렉토리 백업

backupDirectory 함수의 구현 예제입니다.

#include <filesystem>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>

namespace fs = std::filesystem;

std::string getCurrentTimestamp() {
    auto now = std::chrono::system_clock::now();
    auto time = std::chrono::system_clock::to_time_t(now);
    
    std::stringstream ss;
    ss << std::put_time(std::localtime(&time), "%Y%m%d_%H%M%S");
    return ss.str();
}

void backupDirectory(const fs::path& src, const fs::path& backupRoot) {
    try {
        // 타임스탬프로 백업 디렉토리 생성
        fs::path backupPath = backupRoot / (src.filename().string() + "_" + getCurrentTimestamp());
        
        // 재귀 복사
        fs::copy(src, backupPath, 
                 fs::copy_options::recursive | 
                 fs::copy_options::overwrite_existing);
        
        std::cout << "백업 완료: " << backupPath << std::endl;
        
    } catch (const fs::filesystem_error& e) {
        std::cerr << "백업 실패: " << e.what() << std::endl;
    }
}

int main() {
    backupDirectory("project", "backups");
    // 결과: backups/project_20260329_143025/
    return 0;
}

예제 3: 오래된 파일 정리

#include <filesystem>
#include <iostream>
#include <chrono>

namespace fs = std::filesystem;

void cleanupOldFiles(const fs::path& dir, int days) {
    try {
        auto now = fs::file_time_type::clock::now();
        auto threshold = now - std::chrono::hours(24 * days);
        
        int deletedCount = 0;
        
        for (const auto& entry : fs::directory_iterator(dir)) {
            if (entry.is_regular_file()) {
                auto mtime = fs::last_write_time(entry);
                
                if (mtime < threshold) {
                    auto size = fs::file_size(entry);
                    fs::remove(entry.path());
                    
                    std::cout << "삭제: " << entry.path() 
                              << " (" << size << " bytes)" << std::endl;
                    deletedCount++;
                }
            }
        }
        
        std::cout << "총 " << deletedCount << "개 파일 삭제" << std::endl;
        
    } catch (const fs::filesystem_error& e) {
        std::cerr << "에러: " << e.what() << std::endl;
    }
}

int main() {
    cleanupOldFiles("temp", 7);  // 7일 이상 된 파일 삭제
    return 0;
}

예제 4: 파일 동기화

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

void syncDirectories(const fs::path& src, const fs::path& dst) {
    try {
        for (const auto& entry : fs::recursive_directory_iterator(src)) {
            auto relativePath = fs::relative(entry.path(), src);
            auto dstPath = dst / relativePath;
            
            if (entry.is_directory()) {
                // 디렉토리 생성
                fs::create_directories(dstPath);
            } else if (entry.is_regular_file()) {
                // 파일이 없거나 더 최신이면 복사
                if (!fs::exists(dstPath) || 
                    fs::last_write_time(entry) > fs::last_write_time(dstPath)) {
                    
                    fs::copy_file(entry.path(), dstPath,
                                  fs::copy_options::overwrite_existing);
                    std::cout << "동기화: " << relativePath << std::endl;
                }
            }
        }
        
    } catch (const fs::filesystem_error& e) {
        std::cerr << "에러: " << e.what() << std::endl;
    }
}

int main() {
    syncDirectories("source", "destination");
    return 0;
}

5. 자주 발생하는 문제

문제 1: 덮어쓰기 에러

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // ❌ 이미 존재하면 에러
    try {
        fs::copy_file("src.txt", "existing.txt");
    } catch (const fs::filesystem_error& e) {
        std::cerr << "에러: " << e.what() << std::endl;
        // filesystem error: cannot copy file: File exists
    }
    
    // ✅ 옵션 지정
    fs::copy_file("src.txt", "existing.txt",
                  fs::copy_options::overwrite_existing);
    
    return 0;
}

해결책: copy_options를 명시적으로 지정하세요.

문제 2: 디렉토리 삭제 실패

// ❌ 비어있지 않은 디렉토리
try {
    fs::remove("non_empty_dir");  // 실패!
} catch (const fs::filesystem_error& e) {
    std::cerr << e.what() << std::endl;
    // Directory not empty
}

// ✅ 재귀 삭제
int removed = fs::remove_all("non_empty_dir");
std::cout << removed << "개 항목 삭제" << std::endl;

해결책: 비어있지 않은 디렉토리는 remove_all()을 사용하세요.

문제 3: 이동 vs 복사

// 이동 (빠름, 원자적)
try {
    fs::rename("old.txt", "new.txt");
    // 같은 파일시스템 내에서만 가능
} catch (const fs::filesystem_error& e) {
    // 다른 파일시스템이면 실패
    std::cerr << "이동 실패: " << e.what() << std::endl;
}

// 복사 + 삭제 (느림, 비원자적)
fs::copy_file("src.txt", "dst.txt");
fs::remove("src.txt");
// 중간에 실패하면 두 파일이 모두 존재할 수 있음

해결책: 같은 파일시스템 내에서는 rename(), 다른 파일시스템으로는 copy() + remove()를 사용하세요.

문제 4: 예외 처리

#include <filesystem>
#include <iostream>
#include <system_error>

namespace fs = std::filesystem;

// ❌ 예외 무시 (위험)
void deleteFileUnsafe(const fs::path& path) {
    fs::remove(path);  // 실패 시 예외 발생
}

// ✅ try-catch
void deleteFileSafe1(const fs::path& path) {
    try {
        fs::remove(path);
    } catch (const fs::filesystem_error& e) {
        std::cerr << "삭제 실패: " << e.what() << std::endl;
    }
}

// ✅ error_code (예외 없음)
void deleteFileSafe2(const fs::path& path) {
    std::error_code ec;
    bool removed = fs::remove(path, ec);
    
    if (ec) {
        std::cerr << "삭제 실패: " << ec.message() << std::endl;
    } else if (removed) {
        std::cout << "삭제 완료" << std::endl;
    } else {
        std::cout << "파일이 존재하지 않음" << std::endl;
    }
}

해결책: 예외 처리를 항상 고려하거나 error_code 버전을 사용하세요.


6. 원자적 연산

rename의 원자성

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // rename은 원자적 (같은 파일시스템)
    // 성공하거나 실패하거나, 중간 상태 없음
    try {
        fs::rename("old.txt", "new.txt");
        std::cout << "이동 완료 (원자적)" << std::endl;
    } catch (const fs::filesystem_error& e) {
        std::cerr << "이동 실패: " << e.what() << std::endl;
    }
    
    return 0;
}

비원자적 복사

// copy + remove는 비원자적
// 중간에 실패하면 불일치 상태 발생 가능
bool moveFile(const fs::path& src, const fs::path& dst) {
    try {
        // 1. 복사
        fs::copy_file(src, dst);
        
        // 2. 삭제 (여기서 실패하면 두 파일 모두 존재)
        fs::remove(src);
        
        return true;
    } catch (const fs::filesystem_error& e) {
        std::cerr << "이동 실패: " << e.what() << std::endl;
        return false;
    }
}

원자적 이동 패턴:

bool atomicMove(const fs::path& src, const fs::path& dst) {
    try {
        // 같은 파일시스템이면 rename (원자적)
        fs::rename(src, dst);
        return true;
    } catch (const fs::filesystem_error&) {
        // 다른 파일시스템이면 copy + remove
        try {
            fs::copy_file(src, dst);
            fs::remove(src);
            return true;
        } catch (const fs::filesystem_error& e) {
            std::cerr << "이동 실패: " << e.what() << std::endl;
            return false;
        }
    }
}

7. 파일 연산 비교

연산함수원자성파일시스템 간속도
복사copy_file()느림
이동rename()빠름
삭제remove()-빠름
재귀 삭제remove_all()-느림

8. 실전 예제: 파일 관리자

#include <filesystem>
#include <iostream>
#include <vector>

namespace fs = std::filesystem;

class FileManager {
public:
    // 파일 복사 (안전)
    bool copy(const fs::path& src, const fs::path& dst) {
        std::error_code ec;
        
        if (!fs::exists(src, ec)) {
            std::cerr << "원본 파일 없음: " << src << std::endl;
            return false;
        }
        
        fs::create_directories(dst.parent_path(), ec);
        fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec);
        
        if (ec) {
            std::cerr << "복사 실패: " << ec.message() << std::endl;
            return false;
        }
        
        return true;
    }
    
    // 파일 이동 (원자적)
    bool move(const fs::path& src, const fs::path& dst) {
        std::error_code ec;
        
        // 먼저 rename 시도 (빠름)
        fs::rename(src, dst, ec);
        
        if (!ec) {
            return true;
        }
        
        // 실패하면 copy + remove
        if (copy(src, dst)) {
            fs::remove(src, ec);
            return !ec;
        }
        
        return false;
    }
    
    // 오래된 파일 정리
    int cleanup(const fs::path& dir, int days) {
        std::error_code ec;
        auto now = fs::file_time_type::clock::now();
        auto threshold = now - std::chrono::hours(24 * days);
        
        int count = 0;
        
        for (const auto& entry : fs::directory_iterator(dir, ec)) {
            if (entry.is_regular_file(ec)) {
                auto mtime = fs::last_write_time(entry, ec);
                
                if (!ec && mtime < threshold) {
                    fs::remove(entry.path(), ec);
                    if (!ec) {
                        count++;
                    }
                }
            }
        }
        
        return count;
    }
    
    // 디렉토리 크기 계산
    uintmax_t directorySize(const fs::path& dir) {
        std::error_code ec;
        uintmax_t size = 0;
        
        for (const auto& entry : fs::recursive_directory_iterator(dir, ec)) {
            if (entry.is_regular_file(ec)) {
                size += fs::file_size(entry, ec);
            }
        }
        
        return size;
    }
};

int main() {
    FileManager fm;
    
    // 파일 복사
    fm.copy("data.txt", "backup/data.txt");
    
    // 파일 이동
    fm.move("temp.txt", "archive/temp.txt");
    
    // 7일 이상 된 파일 정리
    int deleted = fm.cleanup("temp", 7);
    std::cout << deleted << "개 파일 삭제" << std::endl;
    
    // 디렉토리 크기
    auto size = fm.directorySize("project");
    std::cout << "프로젝트 크기: " << size << " bytes" << std::endl;
    
    return 0;
}

정리

핵심 요약

  1. 복사: copy_file(), copy() (재귀)
  2. 이동: rename() (원자적, 같은 파일시스템)
  3. 삭제: remove(), remove_all() (재귀)
  4. 디렉토리: create_directories() (재귀 생성)
  5. 옵션: copy_options (덮어쓰기, 건너뛰기, 업데이트)
  6. 예외: try-catch 또는 error_code 사용

파일 연산 선택 가이드

상황권장 방법이유
같은 파일시스템 이동rename()빠르고 원자적
다른 파일시스템 이동copy() + remove()rename() 불가
백업copy()원본 유지
동기화last_write_time() 비교변경된 파일만
대용량 파일rename() 우선복사 비용 절감

실전 팁

안전성:

  • 항상 예외 처리 (try-catch 또는 error_code)
  • 원본 파일 존재 확인 후 작업
  • 대상 디렉토리 미리 생성 (create_directories)

성능:

  • 이동은 rename() 우선 시도 (빠름)
  • 대용량 파일은 복사 대신 이동
  • 재귀 작업은 recursive_directory_iterator 사용

유지보수:

  • error_code 버전으로 예외 없는 코드 작성
  • 로깅으로 작업 내역 기록
  • 트랜잭션 패턴으로 롤백 가능하게 설계

다음 단계


관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ File Operations | ‘파일 연산’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ File Operations | ‘파일 연산’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. Everything about C++ File Operations : from basic concepts to practical applications. Master key content quickly with ex… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


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

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


이 글에서 다루는 키워드 (관련 검색어)

C++, file-operations, filesystem, C++17, copy 등으로 검색하시면 이 글이 도움이 됩니다.