您当前的位置: 首页 >  c++

DS小龙哥

暂无认证

  • 0浏览

    0关注

    679博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

DS小龙哥 发布时间:2022-02-24 18:06:20 ,浏览量:0

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:%s\n",name.c_str());

	get_FileBaseName2(path2, name);
	printf("name2:%s\n", 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:%s\n", name.c_str());

	return 0;
}

关注
打赏
1664009229
查看更多评论
立即登录/注册

微信扫码登录

0.0456s