前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C/C++编程: 获取路径里的文件名称、后缀名

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

作者头像
DS小龙哥
发布2022-04-08 08:53:49
1.7K0
发布2022-04-08 08:53:49
举报
文章被收录于专栏:嵌入式项目开发

1. 需求

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

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

代码语言:javascript
复制
#include <iostream>

extern "C"
{
#include <stdio.h>
#include <string.h>
#include<windows.h>
#include<shellapi.h>
#include<stdio.h>
#include <string.h>
};
//获取文件的名称
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 <iostream>

extern "C"
{
#include <stdio.h>
#include <string.h>
#include<windows.h>
#include<shellapi.h>
#include<stdio.h>
#include <string.h>
};
//后缀
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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022/02/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 需求
  • 2. 示例代码: 获取文件名称
  • 3. 取后缀
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档