C++文件路径获取文件名,给我代码
时间: 2023-05-13 08:06:00 浏览: 116
可以使用以下代码获取文件路径中的文件名:
```c
#include <stdio.h>
#include <string.h>
int main() {
char path[] = "/home/user/documents/example.txt";
char *filename = strrchr(path, '/') + 1;
printf("Filename: %s\n", filename);
return 0;
}
```
这个程序中,我们使用了 `strrchr` 函数来查找最后一个斜杠字符 `/`,然后将其后面的字符串作为文件名。注意,我们需要将返回的指针加 1,因为它指向的是斜杠字符本身。
相关问题
C++文件路径获取文件名,给我这个功能函数代码
以下是获取文件名的函数代码:
```c
#include <stdio.h>
#include <string.h>
char* getFileName(char* filePath) {
char* fileName = strrchr(filePath, '/');
if (fileName == NULL) {
fileName = strrchr(filePath, '\\');
}
if (fileName == NULL) {
fileName = filePath;
} else {
fileName++;
}
return fileName;
}
```
使用方法:
```c
char* filePath = "/home/user/Documents/example.txt";
char* fileName = getFileName(filePath);
printf("File name: %s\n", fileName);
```
输出结果:
```
File name: example.txt
```
c++ 从文件路径中获取文件名
在Python中,可以使用os模块中的os.path.basename()函数从文件路径中获取文件名。
例如,对于文件路径/home/user/Documents/myfile.txt,可以使用以下代码获取文件名:
```python
import os
path = '/home/user/Documents/myfile.txt'
filename = os.path.basename(path)
print(filename) # 输出:'myfile.txt'
```