C++ 通过文件路径获取文件名

从文件路径中,获取文件名称。比如:"C:\\Users\\Kandy\\Desktop\\data.txt" ---> data.txt。

在C++的范畴,可以通过 strrchr 或者 string 中的查找字符的 find_last_of 来处理。而在Windows环境中,用其他的API来处理,或许会方便很多!

#include <string>
#include <tchar.h>
#include <Shlwapi.h>
#pragma comment( lib, "shlwapi.lib" )


void split_path(const TCHAR* szFullPath, TCHAR* szDrive, TCHAR* szDir, TCHAR* szFileName, TCHAR* szExt)   
{
#if (_MSC_VER <= 1200) // VC6.0
	_tsplitpath(szFullPath, szDrive, szDir, szFileName, szExt);	
#else
	_tsplitpath_s(szFullPath,
		szDrive,
		szDrive ? _MAX_DRIVE : 0,
		szDir,
		szDir ? _MAX_DIR : 0,
		szFileName,
		szFileName ? _MAX_FNAME : 0,
		szExt,
		szExt ? _MAX_EXT : 0);
#endif
}

//
int _tmain(int argc, _TCHAR* argv[])
{
	//
	std::wstring wszPath = ::PathFindFileName(L"c://Program Files//File.txt");
	printf("wszPath : %ls\n\n", wszPath.c_str());

	///_tsplitpath
	TCHAR szPath[MAX_PATH] = {0};
	TCHAR szDrive[MAX_PATH] = {0};
	TCHAR szDir[MAX_PATH] = {0};
	TCHAR szFileName[MAX_PATH] = {0};
	TCHAR szExt[MAX_PATH] = {0};

	std::wstring szDesktop = L"C:\\Users\\Kandy\\Desktop\\data.txt";
	wcscpy(szPath, szDesktop.c_str());

	split_path(szPath, szDrive, szDir, szFileName, szExt);

	printf("szPath : %ls\nszDrive : %ls\nszDir : %ls\nszFileName : %ls\nszExt : %ls\n\n", 
		szPath, szDrive, szDir, szFileName, szExt);


	//strrchr
	std::string path = "D:/3rdparty/data/test.txt";
	//path = "D:\\3rdparty\\data\\test.txt";
	const char *pbuf = strrchr(path.c_str(),'/');//结果:"/test.txt"
	if (pbuf)
	{
		printf("sz_result : %s\n\n", pbuf+1);
	}
	
	//find_last_of
	int pos = path.find_last_of('\\');
	std::string sz_path;
	if (pos != -1)
	{
		sz_path = std::string(path.substr(pos+1));
	}
	else
	{
		pos = path.find_last_of('/');
		sz_path = std::string(path.substr(pos+1));
	}
	printf("sz_path : %s\n", sz_path.c_str());

	system("pause");

	return 0;
}
运行结果:

wszPath : File.txt

szPath : C:\Users\Kandy\Desktop\data.txt
szDrive : C:
szDir : \Users\Kandy\Desktop\
szFileName : data
szExt : .txt

sz_result : test.txt

sz_path : test.txt

©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页