C++获取路径中的文件名有狠多方法,最常见的方法:
使用C++标准库
首先,可以使用C++标准库中的字符串处理函数来获取路径中的文件名。可以通过以下步骤实现:
-
使用字符串分割函数(例如
std::string::find_last_of
、std::string::substr
等)找到路径中最后一个路径分隔符的位置。 -
使用字符串提取函数(例如
std::string::substr
)从该位置提取路径分隔符后的部分作为文件名。
代码如下:
#include <iostream>
#include <string>
std::string GetFileNameFromPath(const std::string& path) {
size_t found = path.find_last_of("/\\"); // 查找最后一个路径分隔符的位置
if (found != std::string::npos) {
return path.substr(found + 1); // 提取路径分隔符后的部分作为文件名
}
return path; // 如果找不到路径分隔符,则直接返回原路径
}
int main() {
std::string path = "images//1/ss.jpg";
std::string filename = GetFileNameFromPath(path);
std::cout << "File name: " << filename << std::endl;
return 0;
}
输出结果是ss.jpg