Demo entry 6645258

cpp

   

Submitted by bailanhua on Oct 09, 2017 at 17:24
Language: C++. Code size: 1.7 kB.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>

using namespace std;

//define the class to be serialized
class A{
public:
    A() {}
    A(int i) {
        this->i = i;
    }
    ~A() {}

    int getI() {
        return i;
    }

    void setI(int i) {
        this->i = i;
    }

    /** member method for serializing
      * @return
      *     true:   succeeded to serialize
      *     false:  failed to serialize
      * @param
      *     path:   path of file which saves the data
     */
    bool serialize(const char* path) {
        int fd = open(path, O_WRONLY|O_CREAT, S_IRWXU);
        //write data
        int res = write(fd, &i, sizeof(int));
        if(res == -1) {
            close(fd);
            return false;
        }
        res = close(fd);
        if(res == -1)
            return false;
        return true;
    }

    /** member method for deserializing
      * @return
      *     true:  succeeded to deserialize
      *     false: failed to deserialize
      * @param
      *     path:   path of file which saves the data
     */
    bool de_serialize(const char* path) {
        int fd = open(path, O_RDONLY, S_IRWXU);
        //read data
        int res = read(fd, &i, sizeof(int));
        if(res == -1) {
            close(fd);
            return false;
        }
        res = close(fd);
        if(res == -1) {
            return false;
        }
        return true;
    }


//member variable
private:
    int i;
};

int main()
{
    //a to be serialized
    A a(101);
    //b to be deserialized
    A b;
    a.serialize("data");
    b.de_serialize("data");
    cout << b.getI() << endl;

    return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).