Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path to binary in C

Tags:

c

path

How can I get the path where the binary that is executing resides in a C program?

I'm looking for something similar to __FILE__ in ruby/perl/PHP (but of course, the __FILE__ macro in C is determined at compile time).

dirname(argv[0]) will give me what I want in all cases unless the binary is in the user's $PATH... then I do not get the information I want at all, but rather "" or "."

like image 642
singpolyma Avatar asked Apr 16 '09 20:04

singpolyma


People also ask

What is path to binary?

Path aliases replace well-known directories with keywords, using a format similar to that of environment variables in Windows. In this way, binary paths of well-known locations become language neutral and independent of the drive where the binary is located.


2 Answers

Totally non-portable Linux solution:

#include <stdio.h>
#include <unistd.h>

int main()
{
  char buffer[BUFSIZ];
  readlink("/proc/self/exe", buffer, BUFSIZ);
  printf("%s\n", buffer);
}

This uses the "/proc/self" trick, which points to the process that is running. That way it saves faffing about looking up the PID. Error handling left as an exercise to the wary.

like image 130
richq Avatar answered Sep 24 '22 08:09

richq


The non-portable Windows solution:

WCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, ARRAYSIZE(path));
like image 27
i_am_jorf Avatar answered Sep 25 '22 08:09

i_am_jorf