C++ path::lexically_relative
Compute a relative path between locations sharing a base.
A simple example
path::lexically_relative
- Start with Start at notes, target notes/a.txt
- Do this Find the relative route
- Result a.txt
Syntax
image.lexically_relative(notes)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 on macOS or Linux with a POSIX shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonLink a course handout to a diagram
A course will move between the teacher’s laptop and the school server. Compute a relative route from its notes folder to a sibling image folder so the handout can still find the same diagram.
#include <unistd.h>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs = std::filesystem;
int main() {
char pattern[] = "/tmp/file-lesson-XXXXXX";
if (!mkdtemp(pattern)) throw std::runtime_error("Cannot create workspace");
fs::path base(pattern);
try {
auto image = base / "images" / "map.png";
std::cout << image.lexically_relative(base / "notes").generic_string() << '\n';
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
../images/map.png
Go up one directory from notes, then enter images and select the diagram.
Locate a rehearsal score
The choir stores each score inside a season folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
Locate a workshop handout
An instructor stores the current template in a class folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
What to watch for
Both paths need compatible roots. The result depends on which directory is the starting point.