Navigating Files with std::filesystem in C++
std::filesystem (C++17, <filesystem>) brings paths, directories, and file metadata into the standard library: path objects compose with /, exists()/is_directory() query, directory_iterator lists folders, and copy/create_directories/remove_all manipulate them — portably across Windows, macOS, and Linux.
Errors arrive as std::filesystem_error exceptions (or error_code overloads that never throw), and path preferred_separator plus absolute()/relative() paper over slash differences. Recursive iteration plus file_size and last_write_time cover most tooling needs without a single platform #ifdef.
Paths compose with /
fs::path p = "logs"; p /= "app.txt"; builds a correct path on every OS — no manual slash handling.
Query before touching
fs::exists(p), fs::is_regular_file(p), fs::file_size(p) inspect without opening anything.
Iterate directories
for (auto& e : fs::directory_iterator(dir)) visits each entry; recursive_directory_iterator walks whole trees.
Expect exceptions
Missing permissions and vanished files throw filesystem_error — or use the error_code overloads for throw-free checks.
#include <iostream>#include <filesystem> namespace fs = std::filesystem; int main() { fs::path dir = "."; int count = 0; for (auto& entry : fs::directory_iterator(dir)) { if (entry.is_regular_file()) ++count; } std::cout << "files here: " << count << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.