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

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

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

2. 示例代码: 获取文件名称代码语言:javascript复制#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:%s\n",name.c_str());

get_FileBaseName2(path2, name);

printf("name2:%s\n", name.c_str());

return 0;

}3. 取后缀代码语言:javascript复制#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:%s\n", name.c_str());

return 0;

}

相关推荐

车膜怎么贴?汽车玻璃膜自己贴步骤图解
365系统维护

车膜怎么贴?汽车玻璃膜自己贴步骤图解

📅 07-18 👁️ 1739
足球新鲜报
365系统维护

足球新鲜报

📅 12-09 👁️ 6393
换缸垫寿命一般是多久?深度解析影响与延长技巧