-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathfile_basename.cpp
More file actions
30 lines (24 loc) · 847 Bytes
/
file_basename.cpp
File metadata and controls
30 lines (24 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <string>
#include <filesystem> //C++17
//https://stackoverflow.com/questions/8520560/get-a-file-name-from-a-path
//C++17
//https://en.cppreference.com/w/cpp/filesystem/path/stem
int main() {
std::string filename = "C:\\MyDirectory\\MyFile.bat";
// Remove directory if present.
// Do this before extension removal incase directory has a period character.
const size_t last_slash_idx = filename.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
{
filename.erase(0, last_slash_idx + 1);
}
// Remove extension if present.
const size_t period_idx = filename.rfind('.');
if (std::string::npos != period_idx)
{
filename.erase(period_idx);
}
// or in C++17
std::cout << std::filesystem::path(filename).stem().string() << std::endl;
return 0;
}