struct anketa
{
int year;
string fio;
};
#include <iostream>
#include <fstream> // std::fstream
using namespace std;
typedef struct
{
int year;
string fio;
} Anketa;
int main ()
{
Anketa anketa;
anketa.year = 1643;
anketa.fio = "Isaac John Newton";
// *** Writing ***
fstream fs;
fs.open ("anketa.dat", std::fstream::out | std::fstream::binary);
fs.write((char*) &anketa.year, sizeof(int));
size_t len = anketa.fio.length();
fs.write((char*) &len, sizeof(size_t));
fs.write(anketa.fio.data(), len);
fs.close();
// *** Reading ***
fs.open ("anketa.dat", std::fstream::in | std::fstream::binary);
fs.read((char*) &anketa.year, sizeof(int));
fs.read((char*) &len, sizeof(size_t));
char buf[len+1];
fs.read(buf, len);
buf[len] = 0;
anketa.fio = buf;
fs.close();
cout << anketa.year << " " << anketa.fio << endl;
return 0;
}
anketa a;
std::ofstream out(file_name);
out.write(reinterpret_cast<char*>(&a), sizeof(a));
// ...
std::ifstream in(file_name);
in.read(reinterpret_cast<char*>(&a), sizeof(a));