c++获取文件路径里最后一个文件
时间: 2023-06-01 19:03:57 浏览: 49
名
要获取文件路径里最后一个文件名,可以使用以下代码:
```python
import os
path = '/path/to/my/file.txt'
filename = os.path.basename(path)
print(filename) # 输出:file.txt
```
这里使用了 `os.path.basename()` 函数来获取路径中的最后一个文件名。如果路径以斜杠结尾,则返回空字符串。
相关问题
c++ 获得文件路径最后一个/后的文件夹名
你可以使用以下代码来获取文件路径中最后一个 "/" 后的文件夹名:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string path = "/Users/Documents/Project/test.txt";
string folderName = "";
size_t index = path.rfind('/');
if (index != string::npos) {
folderName = path.substr(index+1);
}
cout << "Folder Name: " << folderName << endl;
return 0;
}
```
在上面的代码中,我们使用 `rfind()` 函数查找最后一个 "/" 的位置,然后使用 `substr()` 函数从该位置截取字符串直到字符串末尾,即可获取最后一个 "/" 后的文件夹名。
c++中获取路径最后一个
在 C++ 中获取路径中的最后一个文件或文件夹名字,可以使用以下方法:
```cpp
#include <iostream>
#include <string>
#include <filesystem>
std::string getLastElement(const std::string& path) {
std::filesystem::path fsPath(path);
return fsPath.filename().string();
}
int main() {
std::string path = "/path/to/file.txt";
std::string lastElement = getLastElement(path);
std::cout << lastElement << std::endl;
return 0;
}
```
输出结果为:`file.txt`
在上述代码中,我们使用 C++17 中的 `<filesystem>` 标准库来操作文件路径。`getLastElement` 函数接受一个路径字符串,并将其转换为 `std::filesystem::path` 对象。然后,使用 `filename()` 函数获取路径中的最后一个元素,并使用 `string()` 函数将其转换为字符串类型。最后,在 `main` 函数中调用 `getLastElement` 函数并输出结果。