sh-5.1$ cat main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Employee {
public:
Employee(int num = 0, const string &name = "", int age = 0): number(num), name(name), age(age) {}
Employee(ifstream &ifs) {ifs >> *this;}
friend ostream &operator<<(ostream &os, const Employee &e) {
return os << e.number << " " << e.name << " " << e.age;
}
friend ofstream &operator<<(ofstream &ofs, const Employee &e) {
ofs.write((char *)&e.number, sizeof(e.number));
size_t size = e.name.size();
ofs.write((char *)&size, sizeof(size));
ofs.write(e.name.c_str(), size);
ofs.write((char *)&e.age, sizeof(e.age));
return ofs;
}
friend ifstream &operator>>(ifstream &ifs, Employee &e) {
ifs.read((char *)&e.number, sizeof(e.number));
size_t size; ifs.read((char *)&size, sizeof(size));
char buff[size]; ifs.read(buff, size);
e.name = string(buff, buff + size);
ifs.read((char *)&e.age, sizeof(e.age));
return ifs;
}
private:
int number;
string name;
int age;
};
const vector<Employee> load(const string &filename) {
vector<Employee> result;
ifstream ifs(filename);
size_t size; ifs.read((char *)&size, sizeof(size));
for(size_t i = 0; i < size; ++i) result.push_back(Employee(ifs));
return result;
}
void save(const vector<Employee> &v, const string &filename) {
ofstream ofs(filename);
size_t size = v.size();
ofs.write((char *)&size, sizeof(size));
for(size_t i = 0; i < size; ++i) ofs << v[i];
}
ostream &operator<<(ostream &os, const vector<Employee> &v) {
bool flag = false;
for(size_t i = 0; i < v.size(); ++i) {
if(flag) os << std::endl;
flag = true;
os << v[i];
}
return os;
}
int main(void) {
{
vector<Employee> emp = {{11, "张三", 25}, {12, "李四", 33}};
save(emp, "data.dat");
}
vector<Employee> emp = load("data.dat");
cout << emp << endl;
return 0;
}
sh-5.1$ ./main
11 张三 25
12 李四 33
sh-5.1$
|