This site has been retired. For up to date information, see handbook.gnome.org or gitlab.gnome.org.


[Home] [TitleIndex] [WordIndex

The following is a portable way of saving and loading options under both Linux and Windows. Note the use of g_get_home_dir() to get the home directory.

   1 // gob2 syntax
   2 class Foo {
   3     public GtkWidget *
   4     new (int argc, char * argv[]) {
   5         :
   6         // Load settings
   7         selfp->settings_file = g_strdup(slip(g_get_home_dir())+"/"+".myprog.rc");
   8         foo_widget_load_settings(self);
   9         :
  10     }
  11  
  12     public int
  13     load_settings(self)
  14     {
  15         GError *error = NULL;
  16  
  17         /* Create a new GKeyFile object and a bitwise list of flags. */
  18         GKeyFile *keyfile = g_key_file_new();
  19         GKeyFileFlags flags = GKeyFileFlags(0);
  20  
  21         /* Load the GKeyFile from keyfile.conf or return. */
  22         if (!g_key_file_load_from_file (keyfile,
  23                                         selfp->settings_file,
  24                                         flags,
  25                                         &error)) {
  26             return -1;
  27         }
  28  
  29         char *settings_input_dir = g_key_file_get_string(keyfile,
  30                                                          "settings",
  31                                                          "input_dir",
  32                                                          NULL);
  33         :
  34         g_key_file_free(keyfile);
  35     }
  36  
  37     public int
  38     save_settings(self)
  39     {
  40         GKeyFile *keyfile = g_key_file_new();
  41         GError *error = NULL;
  42  
  43         g_key_file_set_value(keyfile,
  44                              "settings",
  45                              "input_dir",
  46                              keyval_escape(gtk_file_chooser_get_filename(
  47                                  GTK_FILE_CHOOSER(selfp->w_input_dir))));
  48         :
  49         gchar *data = g_key_file_to_data(keyfile,NULL, NULL);
  50  
  51         g_file_set_contents(selfp->settings_file,
  52                              data,
  53                              -1,
  54                              &error);
  55         // Ignore errors
  56         if (error) {
  57             g_error_free(error);
  58         }
  59         g_key_file_free(keyfile);
  60     }
  61 }

2024-10-23 10:58