Date: 2025apr3
Update: 2026sep16
Language: C++
Q. C++: Get the basename of an absolute filename
A. With C++17 or later use std::filesystem() like this:
#include <filesystem>
std::string basename(const std::string absfilename) {
return std::filesystem::path(absfilename).filename();
}
Example Use:
int main() {
const char *absolute = "/etc/NetworkManager/system-connections/MyConnection.nmconnection";
const std::string bn = basename(absolute);
printf("The basename of %s is %s\n", absolute, bn.c_str());
}
Output:
The basename of /etc/NetworkManager/system-connections/MyConnection.nmconnection is MyConnection.nmconnection