VC++ PathFindFileName函数,由文件路径获得文件名

时间:2023-03-09 19:37:02
VC++ PathFindFileName函数,由文件路径获得文件名

1.PathFindFileName函数的作用是返回路径中的文件名。

PTSTR PathFindFileName(
__in PTSTR pPath
);

pPath是指向文件路径字符串的指针,函数返回指向文件名的指针(如果找到的话),否则返回指向路径开头的指针。

PathFindFileName既支持Windows下的反斜杆,也支持Unix下的斜杠,还支持斜杆和反斜杠的混合,

例如:

      * Author: Chechen
* Date: 2014/7/24
*/
#include <stdio.h>
#include <Shlwapi.h> int main()
{
char path[] = "C:\\Windows\\System32/notepad.exe";
/* will output "notepad.exe" */
printf("%s\n", PathFindFileName(path));
return ;
}

2.获取指定的系统路径 SHGetSpecialFolderPath

   #include   <shlobj.h>
#pragma comment(lib, "shell32.lib") TCHAR szPath[MAX_PATH];
SHGetSpecialFolderPathNULL,szPath,CSIDL_COMMON_DOCUMENTS, FALSE);
// szPath 就是

3.PathRemoveFileSpec函数

PathRemoveFileSpec函数的作用是将路径末尾的文件名和反斜杠去掉。

例如,我们想获取EXE文件自身所在的文件夹,可以这样写:

#include <stdio.h>
#include <Shlwapi.h>// 使用PathRemoveFileSpec函数

#pragma comment(lib, "shlwapi.lib") //这个库也要有,不然会报链接错误
int main(int argc, char *argv[])
{
//多字节的方法
char self[MAX_PATH];
//方法一:
GetModuleFileName(NULL, self, MAX_PATH);//得到工作路径 例如:C:\\TestDemo\\Debug\\Service.exe
PathRemoveFileSpec(self);//C:\\TestDemo\\Debug
printf("%s\n", self); /*strrchr()函数的作用是:
查找一个字符串在另一个字符串中 末次 出现的位置,并返回从字符串中的这个位置起,一直到字符串结束的所有字符;
如果未能找到指定字符,那么函数将返回False。
*/
//方法二:
char self2[MAX_PATH];
GetModuleFileName(NULL, self2, MAX_PATH);
*strrchr(self2,'\\') = '\0';
printf("%s\n", self2); return ;
}
#include <stdio.h>
#include <Shlwapi.h> int main(int argc, char *argv[])
{
//Unicode的方法
TCHAR text[MAX_PATH];
//方法一:
GetModuleFileName(NULL, text, MAX_PATH);//得到工作路径 例如:C:\\TestDemo\\Debug\\Service.exe
PathRemoveFileSpec(text);//C:\\TestDemo\\Debug /*wcsrchr()函数的作用是:
查找一个字符串在另一个字符串中 末次 出现的位置,并返回从字符串中的这个位置起,一直到字符串结束的所有字符;
如果未能找到指定字符,那么函数将返回False。
*/
//方法二:
TCHAR text2[MAX_PATH];
GetModuleFileName(NULL, text2, MAX_PATH);
*wcsrchr(text2,'\\') = '\0'; return ;
}
TCHAR    szModulePath[MAX_PATH * ];
ZeroMemory(szModulePath, sizeof(szModulePath));
::GetModuleFileName(NULL, szModulePath, _countof(szModulePath) - ); TCHAR *cp = _tcsrchr(szModulePath, _T('\\'));//C:\\TestDemo\\Debug\\
if (*cp)
{
*(cp + ) = _T('\0'); // remove file name
}

4.得到文件扩展名

LPTSTR PathFindExtension( LPCTSTR pPath );

判断文件是否存在

BOOL PathFileExistsW(LPCWSTR pszPath);