C++ boost serialize struct to text

#include <iostream>
#include <ctime>
#include <vector>
#include <unistd.h>
#include <uuid/uuid.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>
#include <ostream>
#include <string.h>

using namespace std;

char *getTimeNow();
static char *dtValue = (char *)malloc(20);
void printTime2();

struct BookStruct
{
public:
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar &BookId;
        ar &BookName;
        ar &BookTitle;
    }

public:
    int BookId;
    string BookName;
    string BookTitle;
};

void structArray3();
void retrieveUuid(char *uuidValue);

int main()
{
    structArray3();
    return 0;
}

void structArray3()
{
    ofstream ofs("log.txt",ios::app);
    boost::archive::text_oarchive oa(ofs);
    char *uuidValue = (char *)malloc(40);

    for (int i = 0; i < 100; i++)
    {
        struct BookStruct bs;
        bs.BookId = i;        
        retrieveUuid(uuidValue);
        strcat(uuidValue,"\n");
        bs.BookName = uuidValue;
        retrieveUuid(uuidValue);
        strcat(uuidValue,"\n");
        bs.BookTitle = uuidValue;
        oa << bs;
    }

    free(uuidValue);

    cout << "Finsihed in structArray3() now is " << getTimeNow() << endl;
}

void retrieveUuid(char *uuidValue)
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID, uuidValue);
}

void printTime2()
{
    for (int i = 0; i < 100; i++)
    {
        cout << getTimeNow() << endl;
        sleep(1);
    }
    free(dtValue);
    cout << "Finsihed in printTime2() and now is " << getTimeNow() << endl;
}

char *getTimeNow()
{
    time_t rawTime = time(NULL);
    struct tm tmInfo = *localtime(&rawTime);
    strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo);
    return dtValue;
}

The key 

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

struct BookStruct
{ 
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar &BookId;
        ar &BookName;
        ar &BookTitle;
    }
 
    int BookId;
    string BookName;
    string BookTitle;
};




ofstream ofs("log.txt",ios::app);
    boost::archive::text_oarchive oa(ofs);

struct BookStruct bs;
oa << bs;

Compile via below command

g++ h1.cpp -o h1 -I. -usr/share/doc/libboost-dev-all  -lboost_serialization -lboost_system -luuid

Run the output  as ./h1

 

posted @ 2021-12-16 16:48  FredGrit  阅读(61)  评论(0编辑  收藏  举报