C++ filesystem path components
Extract the last component of a path and the name of its parent.
A simple example
filesystem path components
- Start with Path notes/a.txt
- Do this Read its final component
- Result a.txt
Syntax
receipt.parent_path().filename()
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
./lessonPrint a receipt name and its folder
A school store receives a path from the checkout system. The receipt printer needs just the filename, while the filing clerk needs the name of the folder that holds it.
#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 {
fs::path receipt = base / "receipts" / "014.txt";
std::cout << receipt.filename().string() << '\n'
<< receipt.parent_path().filename().string() << '\n';
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
014.txt receipts
The final component is the receipt name. Its parent supplies the filing category.
Locate a rehearsal score
The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.
Locate a workshop handout
An instructor stores the current template in a class folder. Build the nested path and read its final name for the screen.
What to watch for
These are pathname operations. A trailing separator or filesystem root may need separate handling.