serialize table of objects

Mar 15, 2012 at 11:13am
Hi.
I have a question about serialize and desarialize dynamic table of object's.
Let's say I have a class CTowar_internal:
class CTowar_internal
{
int a;
int b;
}
...
now I have two funcitions responsible for serialize and desiarialze a table of CTwoar_internal objects:

void Serialize::save(CTowar_internal* tw, int size)
{
ofstream ofs("data.ros", ios::out);
char* buff = new char[sizeof(CTowar_internal) * size];
memcpy(buff,tw,sizeof(CTowar_internal) * size);
ofs.write(buff, sizeof(CTowar_internal) * size);
ofs.flush();
ofs.close();
}
void Serialize::read(CTowar_internal* tw, int size)
{
ifstream ifs("data.ros", ios::in);
char* buff = new char[sizeof(CTowar_internal) * size];
ifs.read((char *)buff, sizeof(CTowar_internal) * size);
memcpy(tw,buff,sizeof(CTowar_internal) * size);
ifs.close();
}

Now let's use that functions:

main()
{
CTowar_internal* tw = new CTowar_internal[3];
// filling fields:
for(int i=0;i<3;i++)
{
tw[i].a = i;
tw[i].b = i+1;
}
//saving table :
save(tw,3);

//now let's create a new table and load saved objects:
CTowar_internal* tw2 = new CTowar_internal[3];
read(tw2,3);

...

And the tw2 table doesn't match tw table. The tw2 table is loaded with trash.
Can anybody tell me why it doesn't work ?
Mar 15, 2012 at 1:49pm
Consider using formatted i/o instead of unformatted i/o. And a std::vector<> instead of a C-style array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct CTowar_internal
{
    int a ;
    int b ;

    inline friend std::ostream& operator<< ( std::ostream& stm, const CTowar_internal& ct )
    { return stm << ct.a << ' ' << ct.b ; }

    inline friend std::istream& operator>> ( std::istream& stm, CTowar_internal& ct )
    {
        int a, b ;
        stm >> a >> b ;
        if(stm) { ct.a = a ; ct.b = b ; }
        return stm ;
    }
};

void Serialize::save( const std::vector<CTowar_internal>& seq, const char* file_name )
{
    std::ofstream file(file_name) ;
    std::copy( seq.begin(), seq.end(),
               std::ostream_iterator<CTowar_internal>( file, "\n" ) ) ;
}

void Serialize::read( std::vector<CTowar_internal>& seq, const char* file_name  )
{
    std::ifstream file(file_name) ;
    std::istream_iterator<CTowar_internal> begin(file), end ;
    seq.assign( begin, end ) ;
}

Topic archived. No new replies allowed.