C++ 获取路径的各个部分

需求:

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);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值