#include <iostream>
#include <direct.h>
#include <stdio.h>
#include <Windows.h>
//Unicode字符集 获取exe/dll所在路径下的目录
std::string GetProgramDir()
{
wchar_t exeFullPath[MAX_PATH]; // Full path
std::string strPath = "";
GetModuleFileName(NULL, exeFullPath, MAX_PATH);
char CharString[MAX_PATH];
size_t convertedChars = 0;
wcstombs_s(&convertedChars, CharString, MAX_PATH, exeFullPath, _TRUNCATE);
strPath = (std::string)CharString; // Get full path of the file
int pos = strPath.find_last_of('\\', strPath.length());
return strPath.substr(0, pos); // Return the directory without the file name
}
//多字节环境下 获取exe所在的路径
//std::string GetProgramDir2()
//{
// char exeFullPath[MAX_PATH]; // Full path
// std::string strPath = "";
//
// GetModuleFileName(NULL, exeFullPath, MAX_PATH);
// strPath = (std::string)exeFullPath; // Get full path of the file
//
// int pos = strPath.find_last_of('\\', strPath.length());
// return strPath.substr(0, pos); // Return the directory without the file name
//}
int main()
{
//获取当前的工作目录
char buffer[MAX_PATH];
_getcwd(buffer, MAX_PATH);
std::cout << buffer << std::endl;
//获取当前的工作目录
wchar_t pBuf[MAX_PATH];
GetCurrentDirectory(MAX_PATH, pBuf);
std::wcout << pBuf << std::endl;
//获取exe或dll所在的路径
wchar_t defaultPath[MAX_PATH];
GetModuleFileName(NULL, defaultPath, MAX_PATH);
std::wcout << defaultPath << std::endl;
std::string str = GetProgramDir();
std::cout << str << std::endl;
system("pause");
return 0;
}
参考博客: