程序如何获得自己的可执行文件名? [英] How can program get executable name of itself?

查看:156
本文介绍了程序如何获得自己的可执行文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

提取当前可执行文件名称

从ini文件读取配置,该文件的名称应该与可执行文件的名称相同,但当然具有其扩展名。所以如果我命名它 myprogram.exe 配置应该是 myprogram.ini ,如果我更改exe的名称

I created a program that reads configuration from ini file, the name of that file should be identical to name of executable but of course with its extension. So If I name it myprogram.exe the config should be myprogram.ini, and if I change name of the exe after compilation it should look accorting to its new name.

我知道可以从 argv [0] 获得程序名称c $ c>但是这只有当它从命令行开始,当它在explorer中被点击时,这个数组是空的。

I know that it is possible to get program name from argv[0] but this works only if it starts from command line, when it is clicked in explorer this array is empty.

当我读到这里的答案它必须使用此功能执行某些操作: http://stackoverflow.com/a/10572632/393087 - 但我可以找不到这个函数的使用的任何好的例子,我是初学者到c + +和一般的函数定义(像在微软页面上呈现)是太难以让我理解,但是当我得到一个工作示例,它是一个快照让我理解。

As I read through the answers here I think it has to do something with this function: http://stackoverflow.com/a/10572632/393087 - But I can't find any good example of usage of that function, I'm very beginner to c++ and general function definitions (like that presented on microsoft pages) are too hard for me to understand, but when I get a working example it is a snap for me to comprehend.

推荐答案

#include <windows.h>
#include <Shlwapi.h>
// remember to link against shlwapi.lib
// in VC++ this can be done with
#pragma comment(lib, "Shlwapi.lib")

// ...

TCHAR buffer[MAX_PATH]={0};
TCHAR * out;
DWORD bufSize=sizeof(buffer)/sizeof(*buffer);
// Get the fully-qualified path of the executable
if(GetModuleFileName(NULL, buffer, bufSize)==bufSize)
{
    // the buffer is too small, handle the error somehow
}
// now buffer = "c:\whatever\yourexecutable.exe"

// Go to the beginning of the file name
out = PathFindFileName(buffer);
// now out = "yourexecutable.exe"

// Set the dot before the extension to 0 (terminate the string there)
*(PathFindExtension(out)) = 0;
// now out = "yourexecutable"

现在你有一个指向base name的可执行文件;请记住它指向 buffer ,所以当 buffer 超出范围 out 无效。

Now in out you have a pointer to the "base name" of your executable; keep in mind that it points inside buffer, so when buffer goes out of scope out is not valid anymore.

这篇关于程序如何获得自己的可执行文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆