All of the interesting technological, artistic or just plain fun subjects I'd investigate if I had an infinite number of lifetimes. In other words, a dumping ground...

Tuesday, 14 July 2009

Easy serialization in C using structs

Normally I use C++ and this would require using Boost::serialization but I think I'll switch my data structure class back to a C structure and use basic C serialization.
Easier?Here is a test program.
The array size of 20000 creates a 625kB file.
(Build on linux with  gcc -Wall -Wextra -o serial serial.c)

#include <stdio.h>
#include <string.h>

typedef struct node_struct {
    char label[20];
    float x;
    float y;
    struct node_struct * other;
} node_t;

#define ARRSIZE 20000
int main()
{

    node_t nodearr[ARRSIZE];
    node_t readnodearr[ARRSIZE];
    int i;
    for (i=0; i < ARRSIZE; ++i) {
        strcpy(nodearr[i].label, "test label");
        nodearr[i].x = i + 2.3;
        nodearr[i].y = i + 4.3 + nodearr[i].x;
        if (i > 0)
            nodearr[i].other = &nodearr[i-1];
        else
            nodearr[i].other = NULL;
        printf("%d %f %f", i, nodearr[i].x, nodearr[i].y);
    }
    FILE* fp = fopen("nodes", "w");
    fwrite(nodearr, sizeof(node_t), ARRSIZE, fp);
    fclose(fp);
    fp = fopen("nodes", "r");
    fread(readnodearr, sizeof(node_t), ARRSIZE, fp);
    fclose(fp);
    int rtn = memcmp(nodearr, readnodearr, ARRSIZE*sizeof(node_t));
    printf("\n------------\n");
    printf("%d %f %f;", 0, nodearr[0].x, nodearr[0].y);
    for (i=1; i < ARRSIZE; ++i) {
        printf("%f %f, %d, %s %f %f;", nodearr[i].other->x, nodearr[i].other->y, i, nodearr[i].label, nodearr[i].x, nodearr[i].y);
    }
    printf("\nrtn %d\n", rtn);
    return 0;
}

No comments:

tim's shared items

Add to Google Reader or Homepage