Filesystem Library
reading
C++17 introduced the filesystem library to deal with paths and file operations.
By creating a path
object, full paths to files can be built up
using /
as an operator, just like we would do on the commandline:
#include <iostream>
#include <filesystem>
int main() {
std::filesystem::path home("/home/zingale");
auto full_path = home / "hello.cpp";
std::cout << full_path << std::endl;
}
Here’s an example of looking at the path and different parts of a filename:
#include <iostream>
#include <filesystem>
int main() {
std::filesystem::path source{"./filesystem_example.cpp"};
std::cout << source << std::endl;
std::cout << std::filesystem::exists(source) << std::endl;
std::cout << source.filename() << std::endl;
std::cout << source.stem() << std::endl;
std::cout << source.extension() << std::endl;
std::cout << std::filesystem::current_path() << std::endl;
std::cout << std::filesystem::absolute(source) << std::endl;
std::cout << std::filesystem::canonical(source) << std::endl;
std::cout << source.root_path() << std::endl;
}