c - GSList of structs -
c - GSList of structs -
i read this thread, helped me figure out dereferencing properly, went , created situation post's answer's author said avoid, haha.
what i'm trying accomplish creation of basic file browser (per book i'm reading). code below supposed reading through directory contents , filling details i've chosen struct
. struct
appended data
fellow member of gslist
. list used populate row info gtktreeview
, , forth.
typedef struct { gchar *name, *size, *date_modified; }fileproperties; //... static void refresh_directory_listing(gtktreeview *treeview) { gtkliststore *store = gtk_list_store_new(num_columns, g_type_string, g_type_string, g_type_string); gslist *files = null; gtktreeiter iter; get_current_directory_contents(&files); for(gslist *current = files; current != null; current = g_slist_next(current)) { gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, file_name, ((fileproperties *) current->data)->name, file_size, ((fileproperties *) current->data)->size, date_modified, ((fileproperties *) current->data)->date_modified, -1); } gtk_tree_view_set_model(treeview, gtk_tree_model(store)); g_object_unref(store); g_slist_free(files); } static void get_current_directory_contents(gslist **files) { gdir *current_dir = g_dir_open(g_get_current_dir(), 0, null); gchar *file_name = null; fileproperties *file = g_malloc(sizeof(fileproperties)); while((file_name = (gchar *) g_dir_read_name(current_dir))) { memset(file, 0, sizeof(fileproperties)); file->name = g_strdup(file_name); file->size = g_strdup_printf("nope"); file->date_modified = g_strdup_printf("nuh uh"); *files = g_slist_append(*files, file); } g_free(file); }
working understand why file names homecoming blank , has same memory address, it's obvious me g_slist_append()
handing fileproperties
construction on directly. so, references same struct
keeps getting overwritten , freed. whoops.
my question this: appropriate way hand gslist
of struct
's , forth between functions?
you allocating one fileproperties
construction before while
loop, , alter contents of single struct, , append many times.
you need allocate one fileproperties
construction instance each file properties want store.
move allocation within loop, replacing (spurious) memset()
:
while((file_name = (gchar *) g_dir_read_name(current_dir))) { fileproperties *file = g_malloc(sizeof *file); /* rest of loop here ... */ }
c struct glib
Comments
Post a Comment