需求:
1, 在开发过程中,获取当前应用程序的所在路径是比较常见的需求,一般情况下我们封装现有的API进行使用: GetModuleFileName() 。不过,根据具体应用的需求,可能不仅仅要找程序所在的当前路径,也有可能是当前路径的上一层目录,或者其子目录,并且还有需求是获取该应用程序的名字等等。
2,当我们需要对一些文件进行处理时,可能会在该文件目录下生成日志文件,或者是以该文件名称作为关键信息生成其他的文件或文件夹。
当我们遇到类似的问题时,就需要对路径进行解析处理了,当然前提就是找到路径中的各个部分。
其实在windows下已经有了现成的库函数来做这样的操作:
_splitpath()
先看一下该函数的说明:
/***
*_splitpath() - split a path name into its individual components
*
*Purpose:
* to split a path name into its individual components
*
*Entry:
* path - pointer to path name to be parsed
* drive - pointer to buffer for drive component, if any
* dir - pointer to buffer for subdirectory component, if any
* fname - pointer to buffer for file base name component, if any
* ext - pointer to buffer for file name extension component, if any
*
*Exit:
* drive - pointer to drive string. Includes ':' if a drive was given.
* dir - pointer to subdirectory string. Includes leading and trailing
* '/' or '\', if any.
* fname - pointer to file base name
* ext - pointer to file extension, if any. Includes leading '.'.
*
*Exceptions:
*
*******************************************************************************/
使用方法:
TCHAR szPath[_MAX_PATH] = {0}; //完整路径
GetModuleFileName(NULL, szPath, _MAX_PATH);
TCHAR szDrive[_MAX_DRIVE] = {0}; //驱动器名称
TCHAR szDir[_MAX_DIR] = {0}; //路径
TCHAR szFileName[_MAX_FNAME] = {0}; //文件名
TCHAR szFileExt[_MAX_EXT] = {0}; //文件扩展名
_tsplitpath(szPath, szDrive, szDir, szFileName, szFileExt);