C++ I/O 및 파일 조작 - 7. 고급 파일 조작 (Advanced File Manipulation)

2025. 3. 30. 00:54프로그래밍 언어/C++

 

📘 7. 고급 파일 조작 (Advanced File Manipulation)

C++17부터 표준 라이브러리에 포함된 <filesystem> 헤더를 사용하면
파일과 디렉터리를 객체처럼 다룰 수 있어 고급 파일 조작이 훨씬 간편해졌습니다.


✅ 헤더 및 네임스페이스

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

📌 대부분의 std::filesystem 함수는 fs:: 접두사로 줄여서 사용하는 것이 일반적입니다.


✅ 파일 복사 / 이동 / 삭제 / 이름 변경

🔹 파일 복사

fs::copy("a.txt", "b.txt");
  • b.txt가 없으면 새로 생성되고, 있으면 복사 실패 또는 덮어쓰기(옵션 설정 필요)

🔹 파일 이름 변경 (또는 이동)

fs::rename("old.txt", "new.txt");
  • 파일명을 바꾸거나, 경로를 바꾸어 이동할 수도 있음
    예: fs::rename("file.txt", "backup/file.txt");

🔹 파일 삭제

fs::remove("file.txt");
  • 파일이 존재하지 않으면 false 반환

✅ 디렉터리 내 파일 목록 가져오기

디렉터리 안의 모든 파일 및 하위 디렉터리 목록을 가져오는 방법입니다.

for (const auto& entry : fs::directory_iterator("./")) {
    std::cout << entry.path() << std::endl;
}

📌 출력 예시:

"./file1.txt"
"./subdir"
"./data.csv"

🔹 특정 확장자 필터링 예시

for (const auto& entry : fs::directory_iterator("./")) {
    if (entry.path().extension() == ".txt") {
        std::cout << "텍스트 파일: " << entry.path() << std::endl;
    }
}

✅ 유용한 기타 기능

기능 코드
디렉터리 존재 여부 확인 fs::exists("myfolder") && fs::is_directory("myfolder")
파일 크기 확인 fs::file_size("file.txt")
디렉터리 생성 fs::create_directory("logs")
디렉터리 삭제 fs::remove_all("logs")

✅ 예외 처리 주의사항

std::filesystem 함수들은 대부분 예외(exception) 를 던질 수 있으므로,
안정적인 사용을 위해 try-catch 블록으로 감싸는 것이 좋습니다.

try {
    fs::copy("a.txt", "b.txt");
} catch (const fs::filesystem_error& e) {
    std::cerr << "파일 복사 오류: " << e.what() << std::endl;
}

✅ 정리 요약

기능 함수 예시
복사 fs::copy("src", "dest")
이름 변경 fs::rename("old", "new")
삭제 fs::remove("file")
디렉터리 탐색 fs::directory_iterator("경로")
경로 정보 entry.path().filename(), extension() 등

💡 C++17 이상에서 사용 가능하며, 컴파일 시 -std=c++17 옵션과 함께
일부 컴파일러에서는 <filesystem> 사용을 위해 -lstdc++fs 옵션이 추가로 필요할 수 있습니다 (구버전 GCC 등).