C++ std::filesystem Guide: Paths, Iteration, Permissions, Cross-Platform [#37-1]

C++ std::filesystem Guide: Paths, Iteration, Permissions, Cross-Platform [#37-1]

이 글의 핵심

Compose paths with operator/, iterate directories, normalize paths, and set permissions safely.

Introduction: “works on Linux, breaks on Windows”

Separator & cwd confusion

Hardcoding "/" concatenation can interact badly with \\ mixes; current_path() vs executable-relative paths confuse users.

std::filesystem::path + operator/ builds correct paths per OS.

Topics: scenarios (create_directories, plugin scan, permissions, temp cleanup), path API, iterators, file ops, errors, best practices.


Overview

path → operations → iteration—that is the order the sections below follow.

Compile with -std=c++17.


path operations

filename, stem, extension, parent_path, relative, weakly_canonical, absolute.


Iteration

directory_iterator (one level), recursive_directory_iterator with skip_permission_denied.


File operations

copy_file, rename, remove, file_size, status.


Permissions

permissions(path, perms::owner_read | ...) after creating sensitive files.


Common errors

Mixing separators manually; assuming canonical on non-existent paths; permission errors on traversal—handle filesystem_error.


Production patterns

Config rooted at std::filesystem::path configRoot, create_directories(logPath.parent_path()), scanning dll/so by extension.

Longer listings below expand on the same patterns—use them as copy-paste starting points.

Keywords

std::filesystem, C++17, path, directory_iterator, permissions