How to take the path of the open executable in C

Asked

Viewed 601 times

5

How can I capture the path of the executable in C and place it inside a string?

  • 1

    It’s Linux or Windows?

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

2 answers

5

If you want the path and not just the name, it does not have a universal standard form. You will have to consult the operating system and each has its own way. Since you have not been informed, I will indicate the two main:

Linux:

readlink("/proc/self/exe", buf, bufsize)

Documentation.

Windows

GetModuleFileName(NULL, buf, bufsize)

Documentation.

The argv[0] provides only ./nome, most of the time, it may even provide the way if it is called from other specific places, but it cannot be trusted that it will be called from the proper place to provide the expected response. In addition, the code in which this information is needed may not have access to this variable (it is outside the main() and has not been pushed ahead in any way). So it only works in very specific situations.

4

The main() function, where the program starts running, has the following prototype:

int main (int argc, char *argv[])

The argv[0] string contains the name of the executable, the other strings of the matrix have the other parameters passed in the command line. The value of argc corresponds to the length of argv and generally should not be less than 1, because argv[0] always exists.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.