How do I write cross-platform filesystem code?

Writing cross-platform filesystem code in C++ can be achieved through the use of the C++17 `` library, which provides a set of features for navigating and manipulating the filesystem. By utilizing this library, you can write code that is compatible with various operating systems, such as Windows, Linux, and macOS, without worrying about the underlying differences.

The `` library provides convenient functions for tasks such as creating directories, checking file existence, and iterating through directory contents. To ensure your code is portable, make sure to check for necessary dependencies and leverage conditional compilation if needed.

Here's a simple example of cross-platform code that lists all files in a directory:


#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path dirPath{"./"};

    // Check if the directory exists
    if (fs::exists(dirPath) && fs::is_directory(dirPath)) {
        for (const auto &entry : fs::directory_iterator(dirPath)) {
            std::cout << entry.path().filename() << std::endl;
        }
    } else {
        std::cerr << "Directory does not exist!" << std::endl;
    }
    return 0;
}
    

cross-platform C++ filesystem C++17 directory iteration portable code