Finding the path of the C program

Hi All,
I have a c program called findPath.c in a path /home/harsh/c-Programs/. How can i find the path where the program is stored at runtime?? I have given the following

#include<stdio.h>
int main()
{
system("dirname $0");
return 0;
}

This is resulting in the output as
.
<single dot specifying the current directory>

Try the realpath() function on $0.

This is a common question and there is no completely all-purpose perfect answer because there are a lot of ways code can be invoked... realpath on $0 is a decent start.

Thanks man. found out more than a few ways through which one can find the filename of the executing program. One interesting way was through __FILE__ macro which is passed to the compiler during compilation. Are there any other macros like this that give info about the file being compiled..??
Another method was to se the arg[0] parameter. But i read that the path/file name may be or may not be passed as the 0th argument. Just curious to understand at what scenarios the 0th argument is passed and when it is not passed.. anybody knows?

That will only give you the name of the source file being compiled - it expands to a string, so there's no way it can give you the run-time name of the file.

One example would be an entry in an inet.d file. For example, this line:

tftp        dgram   udp wait    nobody  /usr/sbin/tcpd  /usr/sbin/in.tftpd /srv/tftp

will execute the program /usr/sbin/tcpd, but the first argument to it (i.e. argv[0]) will be "/usr/sbin/in.tftpd".

One reliable way (on Linux 2.2 and later) of finding the pathname of the command executed is by looking at /proc/self/exe, which is a symlink to the executed command. It's not portable (but then neither is realpath()), but if that file doesn't exist you could always fall back on argv[0].

Hi sreeharshasn,

Could you tell us why are interested in getting this path?

TIA,
Lo�c

It is sort of a puzzle.

All right, you make me even more curious :wink: