Last Tuesday, 16th April, I had a pleasure to talk about std::filesystem in our Cracow C++ User Group.

Here are the slides and additional comments.

The Talk

The plan for the presentation was to describe the whole library and build a high-level overview. I also wanted to show examples where the std::filesystem simplifies the code.

As an introduction, I wanted to know what are the tasks related to the filesystem. Is that something common among programmers, or quite a rare thing? (let me know in comments what are your example filesystem tasks)

For example, in my work (a powerful Document Editor, Windows Platform) recently I had to manipulate some paths to load files with dictionaries. Or there was also a task that required to iterate through a directory and look for specific files. Yet working with filesystem is not typical for me, as the most requires elements are already written and working well.

Still, when I have a filesystem-related task I might struggle with the following things:

working with paths as strings - issues when you want to add two paths, replace filenames, find extensions, etc. You have to implement some explicit search for that…

iterating through directories - on Windows there’s an API for that, yet it’s not modern C++ :) I wrote about that in my previous post: How to Iterate Through Directories in C++.

After that part, I showed a few examples of “before and after.”

In both cases, we see how it’s now easy and straightforward with C++17!

After the intro… there was the “concrete” part where I showed all the major elements of the library:

compiler support, #include <filesystem>

the filesystem::path class

class the filesystem::directory_entry class

class directory_iterator and recursive_directory_iterator

and support functions

errors and exceptions

performance notes

In the end, I also showed an example of a simple file watcher - and all credits go to Solarian Programmer for his post and code about that: C++17 Filesystem - Writing a simple file watcher. This app is maybe not suited for production (yet), but it allows you to create a multiplatform solution in a matter of a few lines of code. I think it’s good to know such a possibility and understand it bacis concepts.

During the presentation, we also discussed several things (that were quite hard to explain!)

The Slides

Summary

The filesystem is a broad topic! As I see there are two layers to understand:

filesystem OS components, how does it work in general

filesystem API and various design choices

I highly suggest trying std::filesystem as it offers many ways to simplify the code and make it safer. I love the filesystem::path class which offers probably all things you need to compose and work with paths. Without direct string manipulation! And then directory iteration or even creating whole dir tree structures.

Let me know in comments what your everyday tasks related to the filesystem are? Do you use some third-party API? Maybe Boost?