C++17 Filesystem: Usage & Examples
C++17 introduced a standard library that includes a set of classes and functions for managing files and directories in the file system. With this library, it is easy to perform various operations on files and directories, such as creating, copying, moving, deleting files or directories, traversing directories, and obtaining file attributes.
Here are some common uses of the library:
- Create a directory.
#include <filesystem>
std::filesystem::create_directory("path/to/directory");
- Create a file.
#include <filesystem>
std::ofstream file("path/to/file.txt");
- Copy files:
#include <filesystem>
std::filesystem::copy("source_file.txt", "destination_file.txt");
- Move files:
#include <filesystem>
std::filesystem::rename("source_file.txt", "destination_file.txt");
- Delete a file or directory.
#include <filesystem>
std::filesystem::remove("path/to/file_or_directory");
- Traverse directory:
#include <filesystem>
for (const auto& entry : std::filesystem::directory_iterator("path/to/directory")) {
std::cout << entry.path() << std::endl;
}
- Obtain file properties.
#include <filesystem>
std::filesystem::file_status status = std::filesystem::status("path/to/file.txt");
if (std::filesystem::is_regular_file(status)) {
std::cout << "Regular file" << std::endl;
}
These are some common uses in the library that can be flexibly applied according to specific needs. It is important to note that the classes and functions in the library are defined in the std::filesystem namespace.