Filesystem in C++17
source link: https://carlosvin.github.io/langs/en/posts/recursive-directory-iterator/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
In this section, we are going to explain some std::filesystem features with examples, which will help us to highlight differences between C++11 and C++17 so we can get a better idea about what this new library will supply and how it might make developer’s work easier.
std::filesystem::path
Upper we have seen a tiny use case for std::filesystem::path. That is a quite powerful and convenient feature that supplies an multi-platform abstraction for paths to files using the correct directory path separator depending on the platform we are building our application for (\
for Windows based systems and /
for Unix based systems).
Directory separator
When we want our application to use the correct directory separator in C++11, we could use conditional macro declaration:
Directory Separator Operator
std::filesystem::path implements /
operator, which allows to easily concatenate paths to files and directories.
When we want to concatenate paths in C++11, we have to add extra logic to avoid adding duplicate separators and to select the correct separator for target platform:
Checking program output we notice it is not fully correct, we should have checked whether path parts already contains a separator so we don’t append another separator again. That logic is already implemented in std::filesystem::path, so C++17 can be like:
Code is cleaner and just correct, there are no duplicated separators.
Create/Remove Directories
std::filesystem comes with some utilities to create and remove files and directories, but firstly let’s try to do so in C++11.
We have to create/remove one by one. We could rewrite this code snippet with less lines (using a loop), but we still have to pay attention to creation/deletion order, we cannot remove parent directory before we have removed all children.
Since C++17, we can create and remove nested directories with just one call.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK