saving GArray contents to binary file



Hello,

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);
  }
  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?

Greetings, edward




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]