C++ファイルパスからファイル名を取得


ファイルパスからファイル名を取得します.例えば、「C:\Users\Kandy\Desktop\data.txt」--->data.txt.
C++のカテゴリでは、strrchrまたはstringの文字のfind_を検索できます.last_ofで処理します.Windows環境では、他のAPIで処理すると便利かもしれません.
#include 
#include 
#include 
#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

", 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
szDrive : %ls
szDir : %ls
szFileName : %ls
szExt : %ls

", 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

", 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
", 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