#7 Deril
Mozes pouzit nieco taketo:
#include <string>
#include <iostream>
using namespace std;
struct Kniha
{
string nazevKnihy;
string autorJmeno;
string autorPrijmeni;
int pocetStran;
int rokVydani;
void serialize(std::ostream& out)const;
void deserialize(std::istream& in);
void print(std::ostream& out)const{
out << "Kniha[" << nazevKnihy << ", " << autorJmeno << ", " << autorPrijmeni << ", " << pocetStran << ", " << rokVydani << "]\n";
}
};
template<class T>
void binSerialize(std::ostream& out, const T& data){
out.write(reinterpret_cast<const char*>(&data), sizeof(T));
}
template<class T>
void binDeserialize(std::istream& in, T& data){
in.read(reinterpret_cast<char*>(&data), sizeof(T));
}
//specializacia pre string
template<>
void binSerialize<std::string>(std::ostream& out, const std::string& str){
binSerialize(out, str.size());
out << str;
}
//specializacia pre string
template<>
void binDeserialize<std::string>(std::istream& in, std::string& str){
size_t s;
binDeserialize(in, s);
if(s){
str = std::string(s, '\0');
in.read(&str[0], s);
}
}
void Kniha::serialize(std::ostream& out)const{
binSerialize(out, nazevKnihy);
binSerialize(out, autorJmeno);
binSerialize(out, autorPrijmeni);
binSerialize(out, pocetStran);
binSerialize(out, rokVydani);
}
void Kniha::deserialize(std::istream& in){
binDeserialize(in, nazevKnihy);
binDeserialize(in, autorJmeno);
binDeserialize(in, autorPrijmeni);
binDeserialize(in, pocetStran);
binDeserialize(in, rokVydani);
}
#include <fstream>
int main(){
{
std::ofstream file("test.dat", std::ios::binary);
Kniha{"a", "bb", "ccc", 6314, 2000}.serialize(file);
Kniha{"eee", "", "gggg", 123, 1500}.serialize(file);
}
std::ifstream file("test.dat", std::ios::binary);
Kniha kniha[2];
kniha[0].deserialize(file);
kniha[1].deserialize(file);
kniha[0].print(std::cout);
kniha[1].print(std::cout);
return 0;
}