Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the application path in C?

Tags:

c

filepath

gtk

I'm using GTK to create an interface for my C program running Linux.

I'm using this function to load my XML interface:

gtk_builder_add_from_file(builder, g_build_filename("myInterface.glade", NULL), &error);

As long as I'm in the same directory as my compiled file, it works. But if I'm in another directory, let say a child one and I execute it: ../a.out, my program doesn't find the file.

So the idea is to first get the program path ("/home/.../program") and to add the file name to get an absolute path.

But I have no idea how can I get the program path. And I'm not sure this is the best idea to make it work.

Any idea? Thanks!

like image 915
Adrien Neveu Avatar asked Jan 19 '26 11:01

Adrien Neveu


2 Answers

argv[0] contain the relative/full path you ran to run the program.

just scan up to the last '/' and this will be the run dir from your current location

'edit' after some more research, i found this, which works in all cases:

#include<stdio.h>
#include <unistd.h>
#include <string.h>
#include <libgen.h>
int main()
{
  char path[500] = {0};
  int dest_len = 500;
  if (readlink ("/proc/self/exe", path, dest_len) != -1)
    {
        dirname (path);
        strcat  (path, "/");
        printf("path=%s\n", path);
    }
}
like image 184
Shlomi Agiv Avatar answered Jan 22 '26 00:01

Shlomi Agiv


In your case where you are using GTK, it is better to use GResource and compile myInterface.glade directly into your program.

like image 23
ptomato Avatar answered Jan 22 '26 01:01

ptomato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!