[c++] std::filesystem

In C++, the std::filesystem library provides a comprehensive set of classes and functions for manipulating file systems, including paths, regular files, and directories. It was introduced as part of the C++17 standard and simplified tasks related to file and directory operations.

Directory Operations

Creating, deleting, iterating through, and manipulating directories can be achieved using std::filesystem functions. For example, to create a directory, you can use the std::filesystem::create_directory function:

#include <filesystem>
namespace fs = std::filesystem;

int main() {
    fs::create_directory("my_directory");
    return 0;
}

File Operations

Working with files and their attributes, such as checking if a file exists, renaming, copying, or removing files, can easily be done using std::filesystem. For instance, to check if a file exists, you can use the std::filesystem::exists function:

#include <filesystem>
namespace fs = std::filesystem;

int main() {
    if (fs::exists("my_file.txt")) {
        // File exists
    } else {
        // File does not exist
    }
    return 0;
}

Path Operations

The std::filesystem::path class provides methods for working with paths. It simplifies tasks such as joining paths, getting the filename, extension, or parent path, and normalizing paths.

#include <filesystem>
namespace fs = std::filesystem;

int main() {
    fs::path p = "path/to/my_file.txt";
    std::string filename = p.filename();
    std::string parentPath = p.parent_path();
    return 0;
}

Conclusion

The std::filesystem library enhances file system manipulation within C++ programs, simplifying common tasks and providing a more convenient and robust alternative to traditional C-style file I/O operations.

For more detailed information, refer to the C++ standard documentation for std::filesystem.