Skip to content

Instantly share code, notes, and snippets.

@angstyloop
Created March 7, 2023 06:22
Show Gist options
  • Save angstyloop/8d91b4a97d4c15c01e193311d030b879 to your computer and use it in GitHub Desktop.
Save angstyloop/8d91b4a97d4c15c01e193311d030b879 to your computer and use it in GitHub Desktop.
Open a file chooser with GTK 3.
/** file_chooser_dialog.c
*
* Open a file chooser with GTK 3.
*
* COMPILE
* gcc -Wall -o file_chooser_dialog file_chooser_dialog.c `pkg-config gtk+-3.0 --libs --cflags`
*
* EXAMPLE
* ./file_chooser_dialog
*/
#include <gtk/gtk.h>
static void on_response(GtkFileChooserDialog *chooser, int response) {
if (response == GTK_RESPONSE_ACCEPT) {
GFile *file = gtk_file_chooser_get_file(GTK_FILE_CHOOSER(chooser));
gchar* path = g_file_get_path(file);
puts(path);
g_free(path);
g_object_unref(file);
}
g_object_unref(chooser);
}
int main(int argc, char** argv) {
// Initialize GTK
gtk_init(&argc, &argv);
// Create the window
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
// Create the FileChooser
GtkWidget* chooser =
gtk_file_chooser_dialog_new("Open File",
(GtkWindow*) window,
GTK_FILE_CHOOSER_ACTION_OPEN,
"_Cancel",
GTK_RESPONSE_CANCEL,
"_Open",
GTK_RESPONSE_ACCEPT,
NULL);
// Connect the "response" signal handler
g_signal_connect(chooser, "response", G_CALLBACK(on_response), NULL);
// Show the dialog
gtk_widget_show(chooser);
// Start the GTK main loop
gtk_main();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment