Re: saving GArray contents to binary file
- From: Maciej Katafiasz <mnews22 wp pl>
- To: edward hage <edha xs4all nl>
- Cc: gtk-app-devel-list gnome org
- Subject: Re: saving GArray contents to binary file
- Date: Sun, 03 Oct 2004 22:15:41 +0200
Dnia 03-10-2004, nie o godzinie 12:19 +0200, edward hage napisał(a):
I want to save a GArray of struct to a binairy file, but I get stuck somehow.
Just sequentially saving the structs is okay, but I want to save the complete array. Here
is a little program how I tried it, can anyone point out how to succesfully save and load
the GArray. The program is simple so self-explaining.
#include <stdio.h>
#include <stdlib.h>
#include <gtk/gtk.h>
typedef struct // <=== structs like these need to be saved in GArray
{
gchar *brand;
gchar *typenumber;
} typDing;
int main ()
{
const gchar *FILENAME = "ding.txt";
FILE *fp;
GArray *array = g_array_sized_new (FALSE, FALSE, sizeof (typDing), 1);
typDing foo;
guint i;
//assign <== just 3 values with
foo.brand ="1branddasdsadsa";
foo.typenumber = "1typen m asds adsa");
g_array_append_vals (array, &foo, 1);
foo.brand ="2branddasdsadsa";
foo.typenumber = "2typen m asds adsa");
g_array_append_vals (array, &foo, 1);
foo.brand ="3branddasdsadsa";
foo.typenumber = "3typen m asds adsa");
g_array_append_vals (array, &foo, 1);
if ((fp = fopen (FILENAME, "wb")) == NULL)
{
gchar label[90];
g_snprintf (label,90, "Not able to write to %s\n", FILENAME);
printf(label);
return (0);
}
for (i=0; i<array->len; i++)
{
fwrite(&array[i], sizeof (typDing), 1, fp);
^^^^^^^^^
I don't think that's right thing to do, GArray is not C array
}
fclose (fp);
/// read it back
GArray *read_array = g_array_sized_new (FALSE, FALSE, sizeof(typDing), 3);
if ((fp = fopen (FILENAME, "rb")) == NULL)
{
gchar label[90];
g_snprintf (label,90, "Not able to read from %s\n", FILENAME);
printf(label);
return (0);
}
typDing fooread;
for (i=0; i< 3; i++)
{
fread(&fooread, sizeof (typDing), 1, fp);
g_array_append_vals (read_array, &fooread, 1);
g_print("%d: brand:%s\n",i, g_array_index(read_array, typDing, i).brand);
g_print("%d: typen:%s\n",i, g_array_index(read_array, typDing, i).typenumber);
}
fclose (fp);
return (0);
}
I also want to save structs with GArrays inside them, like:
typedef struct
{
gchar *name;
GArray *attached;
} typDing2;
How to save those?
you need to save them struct-by-struct, and then read it back
reconstructing GArray, in general. You could also do some GValue
transformation foo, but that would be probably more hassle than gain, so
unless you have 1000 different types with GArrays that can change at
runtime, better go easy route and just manually save it
HTH,
Maciej
--
"Tautologizm to coś tautologicznego"
Maciej Katafiasz <mnews2 wp pl>
http://mathrick.blog.pl
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]