콘텐츠로 이동

C++ std::filesystem API 활용

#include <filesystem>
namespace fs = std::filesystem;
fs::path p = "/home/user/docs/report.txt";
std::cout << p.root_path(); // /
std::cout << p.parent_path(); // /home/user/docs
std::cout << p.filename(); // report.txt
std::cout << p.stem(); // report
std::cout << p.extension(); // .txt
// 경로 합성
fs::path dir = "/home/user";
fs::path file = dir / "docs" / "report.txt"; // operator/ 로 합성
fs::path p = "data.txt";
if (fs::exists(p)) {
if (fs::is_regular_file(p)) std::cout << "파일\n";
if (fs::is_directory(p)) std::cout << "디렉터리\n";
if (fs::is_symlink(p)) std::cout << "심볼릭 링크\n";
std::cout << "크기: " << fs::file_size(p) << " bytes\n";
auto ftime = fs::last_write_time(p);
}
// 단순 탐색 (비재귀)
for (const auto& entry : fs::directory_iterator("./src")) {
std::cout << entry.path() << '\n';
}
// 재귀 탐색
for (const auto& entry : fs::recursive_directory_iterator("./src")) {
if (entry.is_regular_file() && entry.path().extension() == ".cpp")
std::cout << entry.path() << '\n';
}

파일·디렉터리 생성, 복사, 삭제

섹션 제목: “파일·디렉터리 생성, 복사, 삭제”
// 디렉터리 생성
fs::create_directory("output");
fs::create_directories("a/b/c"); // 중간 경로 자동 생성
// 복사
fs::copy("src.txt", "dst.txt");
fs::copy("src_dir", "dst_dir", fs::copy_options::recursive);
// 이동/이름 변경
fs::rename("old.txt", "new.txt");
// 삭제
fs::remove("file.txt");
fs::remove_all("dir"); // 디렉터리와 내용 전체 삭제
// 심볼릭 링크
fs::create_symlink("target.txt", "link.txt");
// 예외 방식
try {
fs::copy("a.txt", "b.txt");
} catch (const fs::filesystem_error& e) {
std::cerr << e.what() << '\n';
std::cerr << "path1: " << e.path1() << '\n';
}
// 에러 코드 방식 (예외 없음)
std::error_code ec;
fs::copy("a.txt", "b.txt", ec);
if (ec) {
std::cerr << ec.message() << '\n';
}
fs::path tmp = fs::temp_directory_path(); // /tmp (Linux), C:\Temp (Windows)
fs::path abs = fs::absolute("relative/path");
fs::path can = fs::canonical("/path/../to/./file"); // 심볼릭 링크 해석 + 정규화
uintmax_t dirSize(const fs::path& dir) {
uintmax_t total = 0;
for (const auto& entry : fs::recursive_directory_iterator(dir,
fs::directory_options::skip_permission_denied)) {
if (entry.is_regular_file())
total += entry.file_size();
}
return total;
}
fs::permissions("script.sh",
fs::perms::owner_exec | fs::perms::group_exec,
fs::perm_options::add);
auto perms = fs::status("file.txt").permissions();
if ((perms & fs::perms::owner_read) != fs::perms::none)
std::cout << "읽기 가능\n";
  • fs::path로 크로스플랫폼 경로 조작
  • directory_iterator / recursive_directory_iterator로 탐색
  • 예외 방식 또는 std::error_code 방식으로 오류 처리 선택
  • copy_options::recursive로 디렉터리 전체 복사
  • skip_permission_denied로 권한 없는 항목 건너뜀