Filesystem Library in C++17

One of my favorite things about C++ is that it works exceptionally well cross platform. This is entirely to the work of library authors who put a lot of effort into putting a common interface on common tasks, each with a different implementation. The proposed filesystem library in C++ 17, based on the excellent boost filesystem library, in one of my favorite bits. Unfortunately it’s not entirely obvious how to use it without some deep digging. Let me show you how to use it in your project.

Build System

For my example I’m going to manage the build with CMake. My CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.9)


add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} -lstdc++)

The important bits here are the C++ Standard being enforced: C++17, which made the filesystem extension part of the standard library, and explicitly linking with libstdc++. If you’re not using CMake you can still use your build system to acheive those same goals.


To enable the filesystem extension in your code, you’ll need the follow at the top of your file:

#include <experimental/filesystem>
using namespace std::experimental::filesystem;

Hiding the extension in the experimental namespace flumoxed me when I first tried to use the library.

Now if you have a file tree you need to search, you can iterate over it with something like this:

for (auto& p : recursive_directory_iterator(updatepath)) {
	log << p << endl;

There are, of course, many other excellent features of the filesystem extension, this is just the bit I needed for a program I was writing to track a software update process. If you look through the standard you’ll find plenty of other useful functions and objects.

Why This is Important

Navigating the file system is one of the last areas where there were cross platform problems between major operating systems. Since most desktop and server file systems in common usage have hierarchical file systems, there hasn’t been a good reason why we couldn’t have easily interoperable code. Now with this extension as part of the standard, there’s no good reason why we can’t write good cross platform code to deal with the file system. I hope this makes your work easier.


comments powered by Disqus