Cloud
Cloud

Reputation: 19333

Gtk C Application - Set PWD so pictures work

I have a simple Gtk GUI application written in C. I want to be able to render external images within a frame in my main window. The code for this is as follows:

GtkWidget myImage;
myImage = gtk_image_new_from_file("assets/image.png");
gtk_fixed_put(FTK_FIXED(frame), myImage, 0, 0));

The image shows as expected, but only if I cd into the directory where it exists. ie:

cd /tmp/bin/
./gtktest

If I run it from another location, like so, the image is never found.

/tmp/bin/gtktest

Is there a way to have the application set the present working directory (PWD) to the location of the binary itself?

Thank you.

Upvotes: 1

Views: 150

Answers (3)

ptomato
ptomato

Reputation: 57880

Put the assets inside a GResource and compile them directly into your program.

Upvotes: 2

You could call chdir(2) from inside your Gtk program, or its Glib wrapper g_chdir

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158030

You are using a relative path to cwd but you need to use either a relative path based on the location of the program binary or an absolute path based on the filesystem's root like /usr/lib/yourprogram/assets.

If you want to build a relative path based on the location of the binary, which might be more flexible in some situations, then you should use dirname(). Like this:

char *my_location = dirname(argv[0]); // argv[0] contains the path to the binary

Check man 3 dirname for more info.

Upvotes: 2

Related Questions