Finding the path to a executable?

Tommi tommitissari at hotmail.com
Wed Aug 7 00:13:03 PDT 2013


On Wednesday, 7 August 2013 at 05:31:24 UTC, Alan wrote:
> Hello!  This may seem like a simple question, maybe an 
> embarassing question but how would I fetch the absolute path to 
> the directory where my executable is located?  My wording is 
> known to be confusing so I will give an example:
>
> cd ~/projects/program
> dmd Program.d -ofProgram
>
> That executable would be located in /home/alan/projects/program 
> for example.  SO my question is how would I fetch the absolute 
> path to that directory?
>
> Thanks for any help!

This should work on at least couple of systems, but I haven't 
tested this on other than Mac. Also, it's not completely robust, 
because paths could be longer than 4096 chars.

version(Windows) {
     import std.c.windows.windows;
}
else version(OSX) {
     private extern(C) int _NSGetExecutablePath(char* buf, uint* 
bufsize);
}
else version(linux) {
     import std.c.linux.linux;
}
else {
     static assert(0);
}
import std.conv;

// Returns the full path to the currently running executable
string executablePath()
{
     static string cachedExecutablePath;

     if (!cachedExecutablePath) {
         char[4096] buf;
         uint filePathLength;

         version(Windows) {
             filePathLength = GetModuleFileNameA(null, buf.ptr, 
buf.length - 1);
             assert(filePathLength != 0);
         }
         else version(OSX) {
             filePathLength = cast(uint) (buf.length - 1);
             int res = _NSGetExecutablePath(buf.ptr, 
&filePathLength);
             assert(res == 0);
         }
         else version(linux) {
             filePathLength = readlink(toStringz(selfExeLink), 
buf.ptr, buf.length - 1);
         }
         else {
             static assert(0);
         }
         cachedExecutablePath = to!string(buf[0 .. 
filePathLength]);
     }
     return cachedExecutablePath;
}

// Returns the file name of the currently running executable
string executableName()
{
     return executablePath().baseName();
}

// Returns the path to the directory of the currently running 
executable
string executableDirPath()
{
     return executablePath().dirName();
}


More information about the Digitalmars-d mailing list