如何从本机 win32 C++ 应用程序获取当前实例的可执行文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4000877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the current instance's executable file name from native win32 C++ app?
提问by John MacIntyre
Possible Duplicate:
How to get the application executable name in Windows (C++ Win32 or C++/CLI)?
How can I get the current instance's file name & path from within my native win32 C++ application?
如何从本机 win32 C++ 应用程序中获取当前实例的文件名和路径?
For example; if my application was c:\projects\testapps\getapppath.exe it would be able to tell the path is c:\projects\testapps\getapppath.exe
例如; 如果我的应用程序是 c:\projects\testapps\getapppath.exe 它将能够告诉路径是 c:\projects\testapps\getapppath.exe
回答by Garett
You can do this via the GetModuleFileNamefunction.
您可以通过GetModuleFileName函数执行此操作。
TCHAR szFileName[MAX_PATH];
GetModuleFileName(NULL, szFileName, MAX_PATH)
回答by Steve Townsend
GetCurrentProcess, then QueryFullProcessImageName
GetCurrentProcess,然后是QueryFullProcessImageName
Other answers are better for your own process - this is preferred for remote ones. Per the docs:
其他答案更适合您自己的流程 - 这是远程流程的首选。根据文档:
To retrieve the module name of the current process, use the GetModuleFileName function with a NULL module handle. This is more efficient than calling the GetProcessImageFileName function with a handle to the current process.
To retrieve the name of the main executable module for a remote process in win32 path format, use the QueryFullProcessImageName function.
要检索当前进程的模块名称,请使用带有 NULL 模块句柄的 GetModuleFileName 函数。这比使用当前进程的句柄调用 GetProcessImageFileName 函数更有效。
要以 win32 路径格式检索远程进程的主要可执行模块的名称,请使用 QueryFullProcessImageName 函数。
回答by Thanatos
回答by Ed.C
UPDATE: Works only for console applications!
更新:仅适用于控制台应用程序!
The program's path is passed as first argument, It's stored in argv[0]
in the main(argc, argv[])
function.
该方案的路径作为第一个参数传递,它存储在argv[0]
的main(argc, argv[])
功能。
回答by egrunin
Tested:
测试:
int _tmain(int argc, _TCHAR *argv[])
{
_tprintf(L"%s", argv[0]);
return 0;
}
Prints full path.
打印完整路径。