去除路径中的后缀名和获取路径目录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了去除路径中的后缀名和获取路径目录相关的知识,希望对你有一定的参考价值。
首先,记录一个网址,感觉很有用,大部分的文件路径相关函数,里面都有源代码。
https://msdn.microsoft.com/en-us/library/windows/desktop/bb773746(v=vs.85).aspx
1、完整路径,去除后缀名 PathRemoveExtensionA
- #include <iostream>//cout函数所需
- #include "atlstr.h" //PathRemoveExtensionA函数所需
- using namespace std;
- void main(void)
- {
- char buffer_1[] = "C:\\TEST\\sample.txt";
- char *lpStr1;
- lpStr1 = buffer_1;
- cout << "The path with extension is : " << lpStr1 << endl;
- PathRemoveExtensionA(lpStr1);
- cout << "\nThe path without extension is : " << lpStr1 << endl;
- system("pause");
- }
OUTPUT: ================== The path with extension is : C:\TEST\sample.txt The path without extension is : C:\TEST\sample
2、完整文件路径,获得目录
- #include <iostream>//cout函数所需
- #include "atlstr.h" //PathRemoveFileSpecA函数所需
- using namespace std;
- void main(void)
- {
- char buffer_1[] = "C:\\TEST\\sample.txt";
- char *lpStr1;
- lpStr1 = buffer_1;
- cout << "The path with file spec is : " << lpStr1 << endl;
- PathRemoveFileSpecA(lpStr1);
- cout << "\nThe path without file spec is : " << lpStr1 << endl;
- //注意如果获得了目录,需要得到另一个文件路径时
- string filename = lpStr1;
- filename = filename + "\\samle.txt";
- system("pause");
- }
OUTPUT: ================== The path with file spec is : C:\TEST\sample.txt The path without file spec is : C:\TEST
3、获取dll所在路径的两种方式
(1)需要dll入口函数的句柄
- char szPath[MAX_PATH];
- GetModuleFileNameA(dllhandle, szPath, MAX_PATH);//BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) //dll入口函数
(2)无需dll入口函数的句柄,dll内任意函数都可
- EXTERN_C IMAGE_DOS_HEADER __ImageBase;//申明为全局变量
- char DllPath[MAX_PATH] = { 0 };
- GetModuleFileNameA((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath))
以上是关于去除路径中的后缀名和获取路径目录的主要内容,如果未能解决你的问题,请参考以下文章