Use Manipulation Functions with Path
Explore how to manipulate path objects using C++20 filesystem functions, including concatenation, appending, and obtaining absolute and canonical paths. Understand error handling with filesystem_error and how to compare paths for equivalency across different platforms. This lesson equips you with practical skills for robust file system operations in modern C++.
We'll cover the following...
The filesystem library includes functions for manipulating the contents of path objects. In this recipe, we will consider a few of these tools.
How to do it
In this recipe, we examine some functions that manipulate the contents of path objects:
We start with the
namespacedirective and ourformatterspecialization. We do this in every recipe in this chapter:
namespace fs = std::filesystem;template<>struct std::formatter<fs::path>: std::formatter<std::string> {template<typename FormatContext>auto format(const fs::path& p, FormatContext& ctx) {return format_to(ctx.out(), "{}", p.string());}};
We can get the current working directory with the
current_path()function, which returns apathobject:
cout << format("current_path: {}\n", fs::current_path());
Output:
current_path: /usr/include
The
absolute()...