C++17 marks another huge milestone in terms of new features. The filesystem library provides a simpler way of interacting with the filesystem. It was inspired by Boost.Filesystem (available since 2003). This recipe will show its basics features.
Understanding the filesystem
How to do it...
In this section, we'll show two examples of the filesystem library by using directory_iterator and create_directories. Although there is definitely more under this namespace, the goal of these two snippets is to highlight their simplicity:
- std::filesystem::directory_iterator: Let's write the following code:
#include <iostream>
#include <filesystem>
int main()
{
for(auto& p: std::filesystem::directory_iterator("/"))
std::cout << p << std::endl;
}
- Now, compile it with g++ filesystem_01.cpp -std=c++17 -lstdc++fs, where -std=c++17 tells the compiler to use the C++17 standard and -lstdc++fs tells the compiler to use the filesystem library.
The second example is about creating a directory and a file:
- std::filesystem::create_directories: Write the following code:
#include <iostream>
#include <filesystem>
#include <fstream>
int main()
{
std::filesystem::create_directories("test/src/config");
std::ofstream("test/src/file.txt") << "This is an example!"
<< std::endl;
}
- The compilation is as the same as the previous example: g++ filesystem_02.cpp -std=c++17 -lstdc++fs.
With just two lines of code, we've created a folder structure, a file, and have also written on it! It's as simple (and portable) as that.
How it works...
The filesystem library is located in the <filesystem> header under the std::filesystem namespace. These two tests, although pretty simple, were needed to show how powerful the filesystem library is. The output of the first program is as follows:

A complete list of std::filesystem methods can be found here: https://en.cppreference.com/w/cpp/header/filesystem.
std::filesystem::create_directories create a directory (recursively, if test/src does not exist) in the current folder, in this case. Of course, an absolute path is managed too and the current line would be perfectly valid, that is, std::filesystem::create_directories("/usr/local/test/config");.
The second line of the source code uses ofstream to create an output file stream named test/src/file.txt and appends << to the string: This is an example!.
There's more...
The filesystem library is heavily inspired by Boost.Filesystem, which has been available since 2003. If you want to experiment and debug a little, just add the -g option (add the debug symbols to the binary) to the compiler: g++ -g fs.cpp -std=c++17 -lstdc++fs.
See also
The books Effective Modern C++ by Scott Meyers and The C++ Programming Language by Bjarne Stroustrup cover these topics in great detail.