_tsplitpath 函数可以从路径中分解出 盘符、目录、文件名、文件后缀等。是一个非常有用的函数。
Routine | Required header | Compatibility |
---|---|---|
_splitpath | <stdlib.h> | Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 |
_wsplitpath | <stdlib.h> or <wchar.h> | Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 |
errno_t _splitpath_s(
const char * path, //[in]全路径
char * drive, //[out] 驱动器号,后跟一个冒号(:),如果你不需要驱动器号,可以传递NULL
size_t driveNumberOfElements,//[in] Drive的缓冲区大小(单字节或款字节),如果drive为NULL,该参数必须为0
char * dir, //[out] 目录路径,包括尾部的斜杠,可以使用“\”,“/”或者都使用,如果不需要目录路径,可以传递NULL
size_t dirNumberOfElements, //[in] Dir的缓冲区大小(单字节或者款字节),如果dir为NULL,该参数必须为0
char * fname, //[out] 不带扩展名的文件名,如果不需要文件名,可以传递NULL
size_t nameNumberOfElements,//[in]
Fname的缓冲区大小(单字节或者宽字节),如果fname为NULL,该参数必须为0
char * ext, //[out] 文件的扩展名,包括“.”,如果不需要扩展名,可以传递NULL
size_t extNumberOfElements //[in] Ext的缓冲区大小(单字节或者宽字节),如果ext为NULL,该参数必须为0
);
char * ext, //[out] 文件的扩展名,包括“.”,如果不需要扩展名,可以传递NULL
size_t extNumberOfElements //[in] Ext的缓冲区大小(单字节或者宽字节),如果ext为NULL,该参数必须为0
);
返回值:成功返回0,失败返回错误代码 EINVAL
_splitpath_s 该函数将全路径分割成四个部分,分别是驱动器,路径名,文件名(不带扩展名),扩展名。_splitpath_s会根据当前正在使用的多字节页码来识别多字节字符来处理宽字节字符串。_wsplitpath_s是_splitpath_s的多字节版本,_wsplitpath_s的参数是宽字符。
全路径被分成四个部分分别存储在不同的缓冲区中,每个部分允许的最大值为_MAX_DRIVE, _MAX_DIR,_MAX_FNAME, and_MAX_EXT,这些宏定义在stdlib.h中,如果这四个部分的缓冲区大小超过了定义的允许的最大值,那么会引起heap corruption.
- TCHAR szModuleFileName[MAX_PATH] = {0}; // 全路径名
- TCHAR drive[_MAX_DRIVE] = {0}; // 盘符名称,比如说C盘啊,D盘啊
- TCHAR dir[_MAX_DIR] = {0}; // 目录
- TCHAR fname[_MAX_FNAME] = {0}; // 进程名字
- TCHAR ext[_MAX_EXT] = {0}; //后缀,一般为exe或者是dll
- if (NULL == GetModuleFileName(NULL, szModuleFileName, MAX_PATH)) //获得当前进程的文件路径
- return _T("");
- errno_t err = _tsplitpath_s( szModuleFileName,
- drive,
- dir,
- fname,
- ext); //分割该路径,得到盘符,目录,文件名,后缀名
err = _splitpath_s( path_buffer, drive, _MAX_DRIVE, dir, _MAX_DIR, fname,
_MAX_FNAME, ext, _MAX_EXT );