File Systems
C++17 finally gave the standard library a proper answer for files and directories: std::filesystem. No more juggling POSIX on Linux and Win32 on Windows behind your own ifdefs. You get a portable, type-safe interface that plays nicely with exceptions, iterators, and RAII.
Path Manipulation
The std::filesystem::path class smooths over platform differences — separators, drive letters, the lot:
#include <filesystem>#include <iostream>
namespace fs = std::filesystem;
int main() { fs::path p = "/home/user/documents/report.pdf";
std::cout << "Full path: " << p << "\n"; std::cout << "Filename: " << p.filename() << "\n"; // "report.pdf" std::cout << "Stem: " << p.stem() << "\n"; // "report" std::cout << "Extension: " << p.extension() << "\n"; // ".pdf" std::cout << "Parent: " << p.parent_path() << "\n"; // "/home/user/documents" std::cout << "Root: " << p.root_path() << "\n"; // "/"
// Concatenation fs::path dir = "/home/user"; fs::path file = dir / "documents" / "report.pdf"; std::cout << file << "\n"; // "/home/user/documents/report.pdf"
// Replace parts fs::path modified = p; modified.replace_extension(".txt"); std::cout << modified << "\n"; // "/home/user/documents/report.txt"
return 0;}Those quotation marks in the output are real: streaming a path goes through std::quoted, so names with spaces survive a round trip. Call .string() when you want the bare text.
path overloads / to join components, mirroring how POSIX paths read on the page. It's the idiomatic way to build paths in C++ and it picks the right separator for the platform without you thinking about it.
Directory Iteration
#include <filesystem>#include <iostream>
namespace fs = std::filesystem;
void list_directory(const fs::path& dir) { for (const auto& entry : fs::directory_iterator(dir)) { auto& path = entry.path(); if (entry.is_regular_file()) { std::cout << "FILE " << path.filename() << " (" << entry.file_size() << " bytes)\n"; } else if (entry.is_directory()) { std::cout << "DIR " << path.filename() << "/\n"; } else if (entry.is_symlink()) { std::cout << "LINK " << path.filename() << "\n"; } }}
// Recursive iterationvoid list_all_files(const fs::path& dir) { for (const auto& entry : fs::recursive_directory_iterator(dir)) { if (entry.is_regular_file()) { auto relative = fs::relative(entry.path(), dir); std::cout << relative << "\n"; } }}The runner on this site compiles C++14, which predates std::filesystem, so this du-style tool uses the POSIX calls the library wraps: opendir, readdir and lstat. It builds a small tree in a fresh scratch directory, including a symlink that points back up the tree, then prints each directory's total size, biggest first.
File Operations
namespace fs = std::filesystem;
// Check existenceif (fs::exists("myfile.txt")) { /* ... */ }
// Get file sizeauto size = fs::file_size("myfile.txt");
// Copy filefs::copy_file("source.txt", "dest.txt", fs::copy_options::overwrite_existing);
// Copy directory recursivelyfs::copy("src_dir", "dest_dir", fs::copy_options::recursive);
// Create directoriesfs::create_directories("path/to/new/directory");
// Remove files and directoriesfs::remove("file.txt");fs::remove_all("directory_and_contents");
// Rename/movefs::rename("old_name.txt", "new_name.txt");
// Last write timeauto ftime = fs::last_write_time("myfile.txt");Temporary Files
#include <filesystem>#include <stdexcept>#include <string>#include <stdlib.h> // mkstemp (POSIX)#include <unistd.h> // write, close
namespace fs = std::filesystem;
fs::path create_temp_file(const std::string& content) { // mkstemp swaps XXXXXX for random characters and creates the file with // O_CREAT | O_EXCL and mode 0600, all in one step std::string name = (fs::temp_directory_path() / "myapp_XXXXXX").string(); int fd = mkstemp(name.data()); if (fd < 0) throw std::runtime_error("mkstemp failed");
ssize_t written = write(fd, content.data(), content.size()); close(fd); if (written != static_cast<ssize_t>(content.size())) { fs::remove(name); throw std::runtime_error("short write to temp file"); } return name;}The standard library has no portable way to create a temporary file safely, so this one drops to POSIX. Don't be tempted to build the name yourself from a clock or a hash: anyone who can guess the name can plant a symlink there first, and your program will then write wherever it points. mkstemp picks the name and creates the file atomically, failing rather than reusing anything that already exists.
Error Handling
Almost every filesystem function comes in two flavours: one throws on error, the other writes into an std::error_code you supply:
namespace fs = std::filesystem;
// Throwing versiontry { fs::copy_file("src.txt", "dst.txt");} catch (const fs::filesystem_error& e) { std::cerr << "Error: " << e.what() << "\n"; std::cerr << "Path1: " << e.path1() << "\n"; std::cerr << "Path2: " << e.path2() << "\n";}
// Non-throwing versionstd::error_code ec;fs::copy_file("src.txt", "dst.txt", ec);if (ec) { std::cerr << "Error: " << ec.message() << "\n";}Watching for File Changes
The standard library has no inotify/kqueue equivalent, so you have to poll. Crude, but portable:
#include <filesystem>#include <chrono>#include <thread>#include <unordered_map>#include <functional>
namespace fs = std::filesystem;
class FileWatcher { fs::path directory_; std::chrono::milliseconds interval_; std::unordered_map<std::string, fs::file_time_type> file_times_;
public: FileWatcher(const fs::path& dir, std::chrono::milliseconds interval) : directory_(dir), interval_(interval) { for (const auto& entry : fs::recursive_directory_iterator(dir)) { if (entry.is_regular_file()) { file_times_[entry.path().string()] = fs::last_write_time(entry.path()); } } }
void watch(std::function<void(const fs::path&, const std::string&)> callback) { while (true) { std::this_thread::sleep_for(interval_);
// Check for modifications and new files for (const auto& entry : fs::recursive_directory_iterator(directory_)) { if (!entry.is_regular_file()) continue; auto path_str = entry.path().string(); auto mod_time = fs::last_write_time(entry.path());
if (file_times_.find(path_str) == file_times_.end()) { file_times_[path_str] = mod_time; callback(entry.path(), "created"); } else if (file_times_[path_str] != mod_time) { file_times_[path_str] = mod_time; callback(entry.path(), "modified"); } } } }};Practical Example: Finding Duplicate Files
Hashing every file is wasteful: two files can only match if they're the same size, and a size costs one stat. So group by size first, hash only the files that share one, and confirm byte for byte at the end, because std::hash is built for hash tables. It's 64 bits at best, isn't designed to resist collisions, and isn't guaranteed to give the same value across library versions, so treat a match as a hint. A real tool would use SHA-256 or BLAKE3 and read in chunks rather than loading each file whole.
#include <algorithm>#include <cstdint>#include <filesystem>#include <fstream>#include <functional>#include <iostream>#include <iterator>#include <map>#include <string>#include <vector>
namespace fs = std::filesystem;
// A quick in-memory hash: fine for bucketing, not a fingerprintsize_t hash_file(const fs::path& path) { std::ifstream file(path, std::ios::binary); std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); return std::hash<std::string>{}(content);}
bool same_contents(const fs::path& a, const fs::path& b) { std::ifstream fa(a, std::ios::binary), fb(b, std::ios::binary); return std::equal(std::istreambuf_iterator<char>(fa), std::istreambuf_iterator<char>(), std::istreambuf_iterator<char>(fb), std::istreambuf_iterator<char>());}
void find_duplicates(const fs::path& dir) { // Pass 1: group by size std::map<std::uintmax_t, std::vector<fs::path>> by_size; for (const auto& entry : fs::recursive_directory_iterator(dir)) { if (!entry.is_regular_file()) continue; if (entry.file_size() == 0) continue; by_size[entry.file_size()].push_back(entry.path()); }
for (const auto& [size, same_size] : by_size) { if (same_size.size() < 2) continue; // a unique size can't have a twin
// Pass 2: hash only the files that share a size std::map<size_t, std::vector<fs::path>> by_hash; for (const auto& p : same_size) by_hash[hash_file(p)].push_back(p);
for (const auto& [hash, files] : by_hash) { if (files.size() < 2) continue; // Pass 3: equal hashes can still collide, so compare the bytes std::cout << "Duplicates of " << files[0] << ":\n"; for (size_t i = 1; i < files.size(); ++i) { if (same_contents(files[0], files[i])) { std::cout << " " << files[i] << "\n"; } } } }}std::filesystem collapses what used to take hundreds of lines of #ifdef-laden platform code into a few clean calls. Reach for it any time your program touches the disk.