Storing and restrieving objects



Hi,

I am currently doing some tests with storing and restrieving CORBA
objects to and from disk. When defining structures/objects which contain
a lot of elelemnts it is almost impossible to write and read them from a
file, using "text-mode" and saving and retrieving individual elements.

Binary read and write to a file seems the most elegant solution and
seems to work. I made a small testapp to try this first (se below) and
even whaen using this approach with CORBA it works. There is however one
caveat:

e.g. val = fwrite( &testinfo, sizeof( testinfo ), 1, fp );

You need to provide the size with "sizeof" of the structure for both
read and write, how does this behave when the object contains parameters
of type "string" which need to be allocated by:

abc->text = CORBA_string_alloc( 1024 );

or

abc->text = CORBA_string_dup( "-" );

Will the size differ in both cases and what will happen when reading and
writing an object when the size of "string" element was bigger when
written than when read again ?

Best regards,

Peter Van Osta

============================================================

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

static struct {
	double	a;
	int	b;
	char	c[64];
} testinfo;

int main( )
{

	int val = 0;
	FILE *fp = NULL;
	
	fp = fopen( "./test.bin", "wb" );
	
	val = fileno( fp );

	fprintf( stdout, "File ID: %d\n", val );

	testinfo.a = 10.0;
	testinfo.b = 5;
	strcpy( testinfo.c, "test" );
	
	val = fwrite( &testinfo, sizeof( testinfo ), 1, fp );
	
	fprintf( stdout, "Write: %d\n", val );
	
	fclose( fp );

	fp = fopen( "./test.bin", "rb" );

	testinfo.a = 0.0;
	testinfo.b = 0;
	strcpy( testinfo.c, "" );
	
	val = fread( &testinfo, sizeof( testinfo ), 1, fp );
	
	if( ferror( fp ) )
		fprintf( stdout, "Reading file failed\n" );
	
	if( feof( fp ) )
		fprintf( stdout, "Reading file failed on EOF\n" );

	fprintf( stdout, "Read: %d\n", val );

	fprintf( stdout, "%g\t%d\t%s\n", testinfo.a, testinfo.b = 0, testinfo.c
);

	fclose( fp );

	exit( 1 );

}



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