如何获取程序当前执行路径?
因在 ocx 控件中获取执行路径指向的地方不是我需要的地方,故采取获取自身加载的模块路径作为当前程序的执行路径,同时 dll 放在和 ocx 同级目录下。
#include <windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
#pragma execution_character_set("UTF-8")
std::string W2A(const std::wstring & utf8)
{
int buffSize = WideCharToMultiByte(CP_ACP, NULL, utf8.c_str(), -1, NULL, NULL, NULL, FALSE);
char *gbk = new char[buffSize + 1];
memset(gbk, 0, buffSize + 1);
WideCharToMultiByte(CP_ACP, NULL, utf8.c_str(), -1, gbk, buffSize, NULL, FALSE);
std::string result(gbk);
delete[] gbk;
gbk = nullptr;
return result;
}
#if 0
extern "C" __declspec(dllexport) const char* __stdcall W2AEx(wchar_t* utf8)
{
return W2A(utf8).c_str();
}
#endif
std::wstring A2W(const std::string & gbk)
{
int buffSize = MultiByteToWideChar(CP_ACP, NULL, gbk.c_str(), -1, NULL, NULL);
wchar_t* utf8 = new wchar_t[buffSize + 2];
memset(utf8, 0, buffSize + 2);
MultiByteToWideChar(CP_ACP, NULL, gbk.c_str(), -1, utf8, buffSize);
std::wstring result(utf8);
delete[] utf8;
utf8 = nullptr;
return result;
}
#if 0
extern "C" __declspec(dllexport) const wchar_t* __stdcall A2WEx(char* gbk)
{
return A2W(gbk).c_str();
}
#endif
char result[MAX_PATH];
extern "C" __declspec(dllexport) const char* __stdcall OfSelfMoudulPath(char* dynamicLibrary)
{
wchar_t buffer[MAX_PATH] = { 0 };
GetModuleFileName(GetModuleHandle(A2W(dynamicLibrary).c_str()),buffer, MAX_PATH);
std::string::size_type pos = W2A(buffer).find_last_of("\\/");
std::string path = W2A(buffer).substr(0, pos);
//return (path.c_str());
memset(result, 0, MAX_PATH);
strcpy_s(result, path.c_str());
return result;
}
#if 0
std::string HexDump(char * buff, int len)
{
std::stringstream save;
for (unsigned char i = 0; i < len; i++)
{
//44 03 00 d1 56 00 00 05 00 16 60 4a 38 08 81 8e
//44 03 00 D1 56 00 00 05 00 16 60 4A 38 08 81 8E
save << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << ((*(buff + i)) & 0xff);
}
//std::cout << save.str() << std::endl;
return save.str();
}
extern "C" __declspec(dllexport) const char* __stdcall HexDumpEx(char* buff, int len)
{
return HexDump(buff, len).c_str();
}
std::string DeleteChar(const char * buff, int size, unsigned char code)
{
std::vector<char> temp;
//char temp[1024] = { 0 };
int j = 0;
for (int i = 0; i < size; i++)
{
if (*(buff + i) != code)
{
temp.push_back(*(buff + i));
//temp[j] = *(buff + i);
j++;
}
}
temp.push_back(0);
return std::string(temp.data());
}
extern "C" __declspec(dllexport) const char* __stdcall DeleteCharEx(const char * buff, int size, unsigned char code)
{
return DeleteChar(buff, size, code).c_str();
}
#endif
转载请注明出处并保持作品的完整性,谢谢