siddstuff siddstuff -4 years ago 136
C Question

C program, that prints its executable file name

Suppose source code file name is

. When it is compiled, it produce
file. When I execute it, it should identify its file name that is
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);

But, how can I identify the associated file name, in this case which is

Answer Source

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:

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.
Under Windows
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.
Under 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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download