Codectionary / Developer documentation / C++

C++ filesystem path composition

C++17 filesystem::path separates path manipulation from filesystem access. Joining components and inspecting extensions does not require the file to exist.

Syntax

std::filesystem::path output = root / filename;

Examples

C++ filesystem path composition

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <filesystem>
#include <iostream>
int main() {
    std::filesystem::path output = std::filesystem::path("reports") / "summary.csv";
    std::cout << output.filename().string() << '\n';
    std::cout << output.extension().string() << '\n';
    std::cout << output.generic_string() << '\n';
}
  1. Output: summary.csv, .csv, and reports/summary.csv. generic_string uses forward slashes for its textual representation.

Best practices

  • Path normalization is not authorization or a guarantee against traversal and symlinks. Validate untrusted paths against your intended access policy before opening files.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading