1. 程式人生 > >C++中獲取當前執行路徑

C++中獲取當前執行路徑

獲取.exe執行路徑

多位元組集環境下

#include "stdafx.h"
#include <Windows.h>   
#include <iostream>    
#include <string> 
using namespace std;     

string GetProgramDir()   
{    
	char exeFullPath[MAX_PATH]; // Full path 
	string strPath = ""; 

	GetModuleFileName(NULL,exeFullPath,MAX_PATH); 
	strPath=(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 _tmain(int argc, _TCHAR* argv[])
{ 
	string strProgramDir = GetProgramDir();
	cout<<strProgramDir<<endl;

	return 0;
}


Unicode 字符集環境下

#include "stdafx.h"
#include <Windows.h>   
#include <iostream>    
#include <string> 
using namespace std;     

string GetProgramDir()   
{    
	wchar_t exeFullPath[MAX_PATH]; // Full path 
	string strPath = ""; 

	GetModuleFileName(NULL,exeFullPath,MAX_PATH);
	char CharString[MAX_PATH];
	size_t convertedChars = 0;
	wcstombs_s(&convertedChars, CharString, MAX_PATH, exeFullPath , _TRUNCATE);

	strPath=(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 
}    

int _tmain(int argc, _TCHAR* argv[])
{ 
	string strProgramDir = GetProgramDir();
	cout<<strProgramDir<<endl;

	return 0;
}