C++ C++;-如何将正在运行的进程的.exe路径作为std::string获取?

C++ C++;-如何将正在运行的进程的.exe路径作为std::string获取?,c++,windows,C++,Windows,我有一个程序,需要将一个文件放在与已经运行的Windows进程相同的目录中。如何将此目录检索为std::string,以便在正确的位置写入 我知道这不是什么问题,但我用谷歌搜索过很多次,我甚至找不到任何类似的解决方案 编辑:我使用的是Code::Blocks,因此最好的解决方案不是特定于单个IDE的功能。如果您为Windows开发程序,可以使用GetModuleFilename()API调用,然后从整个路径中删除文件名部分。下面是一个例子: #include "stdafx.h" #includ

我有一个程序,需要将一个文件放在与已经运行的Windows进程相同的目录中。如何将此目录检索为std::string,以便在正确的位置写入

我知道这不是什么问题,但我用谷歌搜索过很多次,我甚至找不到任何类似的解决方案


编辑:我使用的是Code::Blocks,因此最好的解决方案不是特定于单个IDE的功能。

如果您为Windows开发程序,可以使用GetModuleFilename()API调用,然后从整个路径中删除文件名部分。下面是一个例子:

#include "stdafx.h"
#include <windows.h>
#include <string>
#include <regex>
using namespace std;

bool MakeNearFilename(const wstring& strPreferredFilename, wstring& strOutputFilename)
{
    WCHAR strExePath[MAX_PATH];
    if (!::GetModuleFileNameW(NULL, strExePath, _countof(strExePath))) {
        return false;
    }

    match_results<const WCHAR*> results;
    if (regex_match(strExePath, results, wregex(L"^(.+\\\\)?(.+?)\\.exe$"))) {
        strOutputFilename = wstring(results[1]) + strPreferredFilename);
    }
    else {
        strOutputFilename = strPreferredFilename;
    }

    return true;
}

int main()
{
    wstring strFilename;
    MakeNearFilename(L"MyProgram.log", strFilename);
    return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
bool MakeNearFilename(const wstring&strPreferredFilename,wstring&strOutputFilename)
{
WCHAR strExePath[MAX_PATH];
if(!::getModuleFileName(NULL,strExePath,_countof(strExePath))){
返回false;
}
匹配结果;
if(regex\u匹配(strExePath,results,wregex(L“^(+\\\\)?(.+?)\\\.exe$”){
strOutputFilename=wstring(结果[1])+strPreferredFilename);
}
否则{
strOutputFilename=strPreferredFilename;
}
返回true;
}
int main()
{
wstring strFilename;
MakeNearFilename(L“MyProgram.log”,strFilename);
返回0;
}

要获取当前进程的路径名,请使用前面提到的
GetModuleFilename

要获取另一个进程的路径名,请使用
GetModuleFileNameEx
。Unicode示例:

#include <Windows.h>
#include <psapi.h>

#pragma comment(lib, "Psapi")

int main()
{
    wchar_t buf[MAX_PATH];
    DWORD pid = 123;
    std::cout << pid << std::endl;
    HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
    if (handle)
    {
        GetModuleFileNameExW(handle, 0, buf, MAX_PATH);
        CloseHandle(handle);
        std::wcout << buf << "\n";
    }

    return 0;
}
#包括
#包括
#pragma注释(lib,“Psapi”)
int main()
{
wchar_t buf[最大路径];
德沃德pid=123;

std::cout可能会在这方面派上用场。谢谢!什么是_countof?我收到了一个“未在此范围内声明”错误,谷歌没有告诉我它是什么的一部分。然后你可以使用或MAX_PATH或sizeof(strExePath)/sizeof(strExePath[0]),而不是_countof(strExePath)。我也得到了“错误:调用'regex\u match(WCHAR[260],std::match\u results&,std::wregex')时没有匹配函数。混合WCHAR和const char*中存在问题。您使用什么?代码编译正常,可能您已经用常用字符串替换了我代码中的unicode字符串。然后您还应该将regex替换为regex(^(.+\\)?(.+?)\.exe$”)它没有为我编译,我也没有做任何更改。我也很难理解这些错误。我按照你的建议将wregex更改为regex,得到了这个错误:“没有匹配的函数来调用'std::basic_regex::basic_regex(const wchar_t[20])”;ps,在Code::Blocks中,Psapi库应该位于%MinGW%\libpsapi.a“