#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;
}

参考博客: 

C++中获取当前运行路径_c++ 获取当前路径_聂炳玉的博客-CSDN博客

C++ 获取当前程序路径_c++获取当前程序的路径_哭哭啼的博客-CSDN博客

更多推荐