Learn C++
#include "ioformatting/filesystem.hpp"

Navigating Files with std::filesystem in C++

//concept

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.

//how it works
1

Paths compose with /

fs::path p = "logs"; p /= "app.txt"; builds a correct path on every OS — no manual slash handling.

2

Query before touching

fs::exists(p), fs::is_regular_file(p), fs::file_size(p) inspect without opening anything.

3

Iterate directories

for (auto& e : fs::directory_iterator(dir)) visits each entry; recursive_directory_iterator walks whole trees.

4

Expect exceptions

Missing permissions and vanished files throw filesystem_error — or use the error_code overloads for throw-free checks.

//example
#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;
}
Output
files here: 3
1The alias fs shortens the long std::filesystem qualifier for the rest of the file.
2directory_iterator yields each entry in the current folder; is_regular_file filters out subdirectories.
3The count prints — here 3 files sat beside the program (your number will vary).
//use cases
Listing, counting, and filtering directory contents portably
Build scripts and file organizers that create, copy, and prune trees
Reading sizes and timestamps for sync and backup tools
Replacing POSIX dirent and Windows FindFile code with one API

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.