How to convert an absolute path to a relative one?

Viewed 84

Let's say I have a base path D:\files and an absolute path D:files\images\1.jpg. Is there a way to convert this absolute path into a relative one with respect to the base path?

1 Answers

Using std::filesystem::relative (C++17 needed)

#include <filesystem>
#include <iostream>

int main() {
    std::cout << std::filesystem::relative("D:files/images/1.jpg", "D:files") << "\n";
    std::cout << std::filesystem::relative("D:files\\images\\1.jpg", "D:files") << "\n";
}

Output

"images\\1.jpg"
"images\\1.jpg"

Demo

Related