C程序,打印其可执行文件名 [英] C program, that prints its executable file name

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

问题描述

假设源代码文件名为 test.cpp .编译后,将生成 test.exe 文件.当我执行它时,它应该标识它的文件名 test.exe 并打印出来.

Suppose source code file name is test.cpp. When it is compiled, it produce test.exe file. When I execute it, it should identify its file name that is test.exe and print it.

我可以使用以下代码获取当前目录中存在的所有文件和目录的列表:

I'm able to get list of all the files and directories present in the current directory using following code:

DIR * directory;
struct dirent * direct;
direct = readdir(directory);

但是,如何识别关联的文件名,在这种情况下为"test.exe" ?

But, how can I identify the associated file name, in this case which is "test.exe"?

推荐答案

构建可执行文件时,您知道它的名称;这最简单的解决方案是使用 -D /D 将其嵌入程序中在命令行上定义宏的选项.

You know the name of the executable when you're building it; the simplest solution is to embed it in the program, using a -D or /D option to define a macro on the command line.

除此之外,通用答案是不可能:

Other than that, the generic answer is that it isn't possible:

根据标准

  • argv [0] 应包含用于调用程序(无论意味着什么).哪个不错,但是1)甚至没有可以在Unix下实现,以及2)在大多数系统下都可以实现别名的意思是用来调用程序的名称带有与可执行文件的名称没有关系.

According to the standard

  • argv[0] should contain the name which was used to invoke the program (whatever that means). Which is nice, but 1) it isn't even implementable under Unix, and 2) under most systems, there are all sorts of aliasing which means that the name used to invoke the program bears no relationship to the name of the executable.
  • 有一个系统函数 GetModuleFileName ,可用于获取可执行文件的 path .一旦有了路,最后一个路径的元素是可执行文件的名称.
  • There's a system function GetModuleFileName which can be used to obtain the path of the executable. Once you've got the path, the last element of the path is the name of your executable.
  • 从根本上讲是不可能的.启动新进程时,Unix为可执行文件的路径以及什么使用不同的参数最终以 argv [0] 结尾,因此它们可能与另一个.这完全取决于谁启动您的流程. bash 将将可执行文件的完整路径放在环境变量"_" 中,因此您可以使用 getenv 来获取它.但这仅在您的程序有效是由 bash 启动的.在大多数Unices上,您也可以在/proc 文件系统(如果您知道该怎么办的话);但是从一个Unix到下一个Unix,其组织方式各不相同.还要注意由于硬链接,您的可执行文件可能不只一个名称.
  • It's fundamentally impossible. When starting a new process, Unix takes separate arguments for the path to the executable and for what ends up in argv[0], so they can potentially have no relationship to one another. It all depends on who starts your process. bash will put the full path to the executable in the environment variable "_", so you can use getenv to get it. But that only works if your program was started by bash. On most Unices, you can also find it in the /proc filesystem, if you know your way around there; but the organization of this varies from one Unix to the next. Note too that because of hard links, you're executable may not have just one name.

真正的问题是为什么要这样做.你怎么了在试图解决?

The real question is why you want to do this. What is the problem you are trying to solve?

这篇关于C程序,打印其可执行文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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