To find the relative path between two absolute paths in C++, you can use the std::filesystem::relative()
 function.
This function computes the relative path from one absolute path to another. Here’s how you can do it:
#include <filesystem>
#include <iostream>
int main() {
std::filesystem::path base{
R"(C:\Users\example\projects)"};
std::filesystem::path target{
R"(C:\Users\example\projects\subdir\file.txt)"};
std::filesystem::path relativePath =
std::filesystem::relative(target, base);
std::cout << "Relative Path: "
<< relativePath.string();
}
Relative Path: subdir\file.txt
std::filesystem::relative(target, base)
to compute the relative path.Relative paths are crucial when you want to specify paths relative to a certain directory, especially in projects that may be moved between different environments. This makes your code more flexible and portable.
std::filesystem::relative()
handles platform-specific path separators, making it a robust solution for cross-platform applications. Whether you’re working on Windows with backslashes (\
) or on Unix-like systems with forward slashes (/
), the function ensures the correct path format.
Ensure both paths are absolute. If you pass relative paths to std::filesystem::relative()
, it will throw an error. Here’s how to handle it:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path base{
R"(C:\Users\example\projects)"};
fs::path target{
R"(C:\Users\example\projects\subdir\file.txt)"};
try {
fs::path relativePath =
fs::relative(target, base);
std::cout << "Relative Path: "
<< relativePath.string();
} catch (const fs::filesystem_error& e) {
std::cerr << "Error: " << e.what();
}
}
Relative Path: subdir\file.txt
Finding the relative path between two absolute paths using std::filesystem::relative()
is straightforward and ensures your paths remain flexible and portable. Always handle exceptions to manage any potential errors gracefully.
Answers to questions are automatically generated and may not have been reviewed.
A guide to effectively working with file system paths, using the path
type within the standard library's filesystem
module.