C++ Filesystem

David Sugar - Aug 23 '23 - - Dev Community

In normalizing c++17 filesystem use in my code, I found it much nicer than my experiences with rust's equivalent might suggest. From rust I kept having to unwrap layers and convert string types a lot. std::filesystem::path and directory_entry may even have as many layers and complexity as rusts, but it feels much easier and more automatic to actually work with. I especially appreciate I can write a directory scan as a stl algorithm and execute filenames in a lambda. For example:

namespace fsys = std::filesystem;
inline auto scan_dir(const fsys::path& path, std::function<bool(const fsys::directory_entry&)> proc) {
    auto dir = fsys::directory_iterator(path);
    return std::count_if(begin(dir), end(dir), proc);
}
Enter fullscreen mode Exit fullscreen mode

What kept me from using c++17 filesystem support was poor gcc support for a long time, including having it as a separate runtime library, and it's similarly late introduction in clang. I currently have similar problems with adapting use of c++20 modules, but probably will rewrite things using that in a few years, as, like header libraries, it makes auto type deduction much more valuable. Header-less code means less duplication, and to me it would make c++ even more preferable to coding than rust.

Whats important to remember is that many enterprise gnu/linux distros have very long lifespans. They keep older compilers and versions of languages alive a lot longer with them, too. I now target bullseye (debian 11/gcc 10) or later, though my code can still build on suse (including openSUSE leap) and netbsd 9, both of which still default with gcc < 10 and c++ libraries built from that. Old system releases never die...

. . . . . . . .
Terabox Video Player