Library contents

C++ std::filesystem::path

Join a receipts folder and a filename, then print the filename component.

A simple example

std::filesystem::path

  1. Start with Directory notes and name a.txt
  2. Do this Join the two path components
  3. Result notes/a.txt on Unix
The path API uses the separator for the host operating system.

Syntax

C++ syntax
(std::filesystem::path("receipts") / "today.txt").filename().string()
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
./lesson

Build a receipt path without hard-coded separators

A receipt export must work on machines with different directory separators. Build the destination from its folder and filename components so each operating system can represent it correctly.

Resulttoday.txt
lesson.cpp
#include <filesystem>
#include <iostream>

int main() {
    std::cout << ((std::filesystem::path("receipts") / "today.txt").filename().string()) << "\n";
    return 0;
}
Output
today.txt

The joined path contains a receipts directory and today.txt. Reading its final component works independently of the full path used on the computer.

Advertisements

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.

Givenspring / alto.txt
Worked resultalto.txt

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.

Givenceramics / glaze.pdf
Worked resultglaze.pdf

What to watch for

Use relative child names when joining paths. An absolute child can replace the parent on some platforms.

Documentation for std::filesystem::path