去除路径中的后缀名和获取路径目录

本文介绍如何使用Windows API函数处理文件路径,包括去除文件扩展名、获取文件所在目录及获取DLL所在路径的方法。提供了详细的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,记录一个网址,感觉很有用,大部分的文件路径相关函数,里面都有源代码。

https://msdn.microsoft.com/en-us/library/windows/desktop/bb773746(v=vs.85).aspx 

1、完整路径,去除后缀名   PathRemoveExtensionA

 

[cpp]  view plain  copy
 
  1. #include <iostream>//cout函数所需  
  2. #include "atlstr.h"  //PathRemoveExtensionA函数所需  
  3.   
  4. using namespace std;  
  5.   
  6. void main(void)  
  7. {  
  8.     char buffer_1[] = "C:\\TEST\\sample.txt";  
  9.     char *lpStr1;  
  10.     lpStr1 = buffer_1;  
  11.     cout << "The path with extension is          : " << lpStr1 << endl;  
  12.     PathRemoveExtensionA(lpStr1);  
  13.     cout << "\nThe path without extension is       : " << lpStr1 << endl;  
  14.     system("pause");  
  15. }  
OUTPUT:
==================
The path with extension is          : C:\TEST\sample.txt
The path without extension is       : C:\TEST\sample

 

2、完整文件路径,获得目录

 

[cpp]  view plain  copy
 
  1. #include <iostream>//cout函数所需  
  2. #include "atlstr.h"  //PathRemoveFileSpecA函数所需  
  3.   
  4. using namespace std;  
  5.   
  6. void main(void)  
  7. {  
  8.     char buffer_1[] = "C:\\TEST\\sample.txt";  
  9.     char *lpStr1;  
  10.     lpStr1 = buffer_1;  
  11.     cout << "The path with file spec is          : " << lpStr1 << endl;  
  12.     PathRemoveFileSpecA(lpStr1);  
  13.     cout << "\nThe path without file spec is       : " << lpStr1 << endl;  
  14.     //注意如果获得了目录,需要得到另一个文件路径时  
  15.     string filename = lpStr1;  
  16.     filename = filename + "\\samle.txt";  
  17.     system("pause");  
  18. }  

 

OUTPUT:
==================
The path with file spec is          : C:\TEST\sample.txt
The path without file spec is       : C:\TEST

3、获取dll所在路径的两种方式

(1)需要dll入口函数的句柄

 

[cpp]  view plain  copy
 
  1. char szPath[MAX_PATH];  
  2. GetModuleFileNameA(dllhandle, szPath, MAX_PATH);//BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) //dll入口函数  

 

(2)无需dll入口函数的句柄,dll内任意函数都可

 

[cpp]  view plain  copy
 
  1. EXTERN_C IMAGE_DOS_HEADER __ImageBase;//申明为全局变量  
  2. char   DllPath[MAX_PATH] = { 0 };  
  3. GetModuleFileNameA((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath))

转载于:https://www.cnblogs.com/wangjian8888/p/8004491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值