欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

C/C++编程:获取路径里的文件名称、后缀名

时间:2023-04-24
1、需求

windows下使用C/C++编写一个方法,传入文件的完整路径,取出文件的基本名称,后缀名等数据。

2、示例代码: 获取文件名称

#include extern "C"{#include #include #include#include#include#include };//获取文件的名称void get_FilebaseName1(char *path, std::string &name){char *p=path+strlen(path)-1;while (p!= path){if (*p == '\' || *p == '/'){p++; //向前加一位,去掉斜杠name = p;return;}p--;}name = p;}//获取文件的名称void get_FilebaseName2(std::string path, std::string &name){for (int i= path.size()-1;i>0;i--){if (path[i] == '\' || path[i] == '/'){name=path.substr(i+1);return;}}name = path;}int main(){std::string name;char path[] = "D:/123/456/1.c";char path2[] = "D:\123\456\2.c";get_FilebaseName2(path,name);printf("name1:%sn",name.c_str());get_FilebaseName2(path2, name);printf("name2:%sn", name.c_str());return 0;}

3、取后缀

#include extern "C"{#include #include #include#include#include#include };//后缀void get_FileSuffix(std::string path, std::string &suffix){for (int i = path.size() - 1; i > 0; i--){if (path[i] == '.'){suffix = path.substr(i + 1);return;}}suffix = path;}int main(){std::string name;char path[] = "D:/123/456/1.c";char path2[] = "D:\123\456\2.c";get_FileSuffix(path2, name);printf("name3:%sn", name.c_str());return 0;}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。