您的位置:首页 > 编程语言 > C语言/C++

C++中获取当前运行路径

2015-11-15 23:58 295 查看
获取.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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: