Home > database >  How to convert an absolute path to a relative one?
How to convert an absolute path to a relative one?

Time:07-14

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?

CodePudding user response:

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