1. 程式人生 > >去除路徑中的後綴名和獲取路徑目錄

去除路徑中的後綴名和獲取路徑目錄

targe tails pac 獲得 ces 源代碼 cout cal 全局變量

首先,記錄一個網址,感覺很有用,大部分的文件路徑相關函數,裏面都有源代碼。

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. using namespace std;
  4. void main(void)
  5. {
  6. char buffer_1[] = "C:\\TEST\\sample.txt";
  7. char *lpStr1;
  8. lpStr1 = buffer_1;
  9. cout << "The path with extension is : " << lpStr1 << endl;
  10. PathRemoveExtensionA(lpStr1);
  11. cout << "\nThe path without extension is : " << lpStr1 << endl;
  12. system("pause");
  13. }
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. using namespace std;
  4. void main(void)
  5. {
  6. char buffer_1[] = "C:\\TEST\\sample.txt";
  7. char *lpStr1;
  8. lpStr1 = buffer_1;
  9. cout << "The path with file spec is : " << lpStr1 << endl;
  10. PathRemoveFileSpecA(lpStr1);
  11. cout << "\nThe path without file spec is : " << lpStr1 << endl;
  12. //註意如果獲得了目錄,需要得到另一個文件路徑時
  13. string filename = lpStr1;
  14. filename = filename + "\\samle.txt";
  15. system("pause");
  16. }

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

去除路徑中的後綴名和獲取路徑目錄