faulty tutorial?

Hello!

I used this turoial http://www.functionx.com/cpp/articles/serialization.htm to learn binary serialization, but it does not seem to be working! Creating files is no problem, but when reading them, the data is not the same as the one you put in!

Here is my code: (I am getting the same result when using this code as when compiling and running the code in the example. This code is more clean)

main.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdlib.h>
#include <string>
#include <fstream>
#include <iostream>
#include "Badger.h"

using namespace std;

void WriteObjectToFile(string url, Badger obj) {
    ofstream ofs(url.c_str(), ios::binary);
    if (ofs.is_open()) {
        cout << "Creating file " << url << endl;
        ofs.write((char *) & obj, sizeof (obj));
    } else {
        cout << "Failed creating file " << url << endl;
    }
}

Badger readBadgerFromFile(string url) {
    Badger returnBadger;
    ifstream ifs(url.c_str(), ios::binary);
    if (ifs.is_open()) {
        ifs.read((char *) & returnBadger, sizeof (returnBadger));
    }
}

void removeObjectFile(string url) {
    remove(url.c_str());
    cout << "Removing " << url << endl;
}

int main(int argc, char** argv) {
    Badger b0;
    b0.age = 12;
    string url = "/home/henke/Desktop/someName.bin";
    WriteObjectToFile(url, b0);

    Badger b1 = readBadgerFromFile(url);

    if (b0.age == b1.age) {
        cout << "Algorithm seems to be working\n";
    } else {
        cout << "Algorith does not seem to be working!!\n";
    }

    removeObjectFile(url);


    return (EXIT_SUCCESS);
}


badger.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef _BADGER_H
#define	_BADGER_H

class Badger {
public:
    Badger();
    Badger(const Badger& orig);
    virtual ~Badger();
    int age;
private:

};

#endif	/* _BADGER_H */ 


output
1
2
3
Creating file /home/henke/Desktop/someName.bin
Algorith does not seem to be working!!
Removing /home/henke/Desktop/someName.bin


Why is the input not the same as the output?

Thanks in advance!
ofs.write((char *) & obj, sizeof (obj));
That line is directly writing to the file what is in the memory occupied by the object.
It won't be portable and it will cause trouble to virtual tables or dynamically allocated members.
NEVER do that
For serialization in C++ check the boost libraries ( as I already suggested here http://www.cplusplus.com/forum/beginner/25721/#msg136731 )

BTW you are not returning anything from readBadgerFromFile
Last edited on
Ok, boost it is then!

BTW you are not returning anything from readBadgerFromFile

hehe, Java would give NullPointer for that :)

Thanks for your answer
Topic archived. No new replies allowed.