天天看點

C++ 檔案路徑操作相關函數、擷取dll所在的路徑

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

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

繼續閱讀