取当前EXE程序所在路径的C++示例代码

直接贴源代码

/*
Title: 取当前EXE程序所在的路径
Date: 2018-12-25
Author: kagula
Test Environment:
[1]Win10Pro, Visual Studio Community 2017 with update 5.
[2]CentOS7, gcc 5.5.
*/

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif // _WIN32_


#include <iostream>

#ifdef _WIN32

std::string GetExePath()
{
	std::string sFullPath;//全路径,例如:"D:\program files\a.exe"
	std::string sBarePath;//不含程序名路径,例如: "D:\program files"

	char chpath[MAX_PATH];
	GetModuleFileNameA(NULL, (LPTSTR)chpath, sizeof(chpath));
	sFullPath = chpath;
	std::string::size_type nPos = sFullPath.find_last_of("\\");
	if (nPos != std::wstring::npos)
	{
		sBarePath = sFullPath.substr(0, nPos);
		sBarePath.append("\\");
	}

	return sBarePath;
}
#else
/*
**函数功能:获取当前可执行文件的执行路径个文件名
**    入参:processdir 存放可执行文件路径
**    入参:processname 存放可执行文件名字
**    入参:len 入参:processdir的长度
**  返回值:可执行路径的长度
*/
std::string GetExePath()
{
	char processdir[256];
	char* filename;
        int   len = sizeof(processdir);
	if (readlink("/proc/self/exe", processdir, len) <= 0)
	{
		return std::string();
	}
	if (len >= 0)
	{
		processdir[len] = '/';
	}

	std::string exe_path = processdir;

	size_t nPos = exe_path.find_last_of("/");
	if (nPos > 0)
	{
		exe_path = exe_path.substr(0, nPos);
		exe_path.append("/");
	}
	return exe_path;
}
#endif

int main()
{

	using namespace std;

	cout << GetExePath().c_str() << endl;

#ifdef _DEBUG
	cin.get();
#endif
	return 0;
}

CMakeLists.txt清单

#设置项目名称
PROJECT(testGetEXEFileDir)
 
#要求CMake的最低版本为2.8
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)

#指定可执行程序输出路径为运行cmake时路径的bin子路径
#默认是输出到运行cmake命令时的路径
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
MESSAGE(STATUS "ls EXECUTABLE_OUTPUT_PATH: " ${EXECUTABLE_OUTPUT_PATH})

#CMake运行时,打印路径
MESSAGE(STATUS "PROJECT_SOURCE_DIR: " ${PROJECT_SOURCE_DIR})
MESSAGE(STATUS "PROJECT_BINARY_DIR: " ${PROJECT_BINARY_DIR})
 
#添加头文件搜索路径
INCLUDE_DIRECTORIES(/usr/local/include)
 
#添加库文件搜索路径
LINK_DIRECTORIES(/usr/local/lib)
LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/../lib)

#如果以"cmake -D DEBUG_MODE=ON .."形式调用cmake
#则为C++源文件设置_DEBUG宏
IF(DEBUG_MODE)
  ADD_DEFINITIONS(-D_DEBUG)
ENDIF()
 
#用于将当前目录下的所有源文件的名字保存在变量 DIR_SRCS 中
AUX_SOURCE_DIRECTORY(. DIR_SRCS)
 
ADD_EXECUTABLE(testGetEXEFileDir ${DIR_SRCS})
TARGET_LINK_LIBRARIES(testGetEXEFileDir)

猜你喜欢

转载自blog.csdn.net/lee353086/article/details/85248496