从C中的路径拆分文件名
我是C新手,但擅长python。 我正在寻找function相当于C中的string.split(“/”)[ – 1]函数。到目前为止,我已经能够创建一个具有我整个路径的字符数组。 我想拆分该字符串,所以我只有文件名。 下面我列出了一个样本
char input_file_path [1024] strcpy(input_file_path, "/this/is/my/file/path.txt")
我想要一些带有input_file_path的函数,然后从中分离出path.txt。 谢谢!
您正在寻找basename(3)
:
basename()
函数返回path指向的路径名中的最后一个组件,删除任何尾随的’/
‘字符。
例:
#include #include int main(void) { char path[] = "/this/is/my/file/path.txt"; char *file = basename(path); printf("%s\n", file); return 0; }
构建和运行:
$ make example && ./example cc example.c -o example path.txt
试试strtok()
。
用命令man strtok
查找。 man
页是学习C的好指南,无需退出命令行的安全性。
http://en.cppreference.com/w/c/string/byte/strtok
点击这里 这也是C和C ++代码的一个很好的参考。