- 性别
- 保密
- 积分
- 733
- 积分
- 2253
- 精华
- 10
- 阅读权限
- 200
- 注册时间
- 2012-4-27
- 最后登录
- 2023-12-28
- 帖子
- 328
- 性别
- 保密
|
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- using namespace std;
- struct test
- {
- string name;
- int id;
- int age;
- };
- void print_test(const test &t)
- {
- cout << "Name: " << t.name << endl;
- cout << "ID: " << t.id << endl;
- cout << "Age: " << t.age << endl << endl;
- }
- int main()
- {
- test t[2];
- ofstream out("out.dat", ios::out);
- if (!out)
- {
- cerr << "File open error!";
- return 1;
- }
- t[0].name = "Name1";
- t[0].id = 101;
- t[0].age = 20;
- t[1].name = "Name2";
- t[1].id = 102;
- t[1].age = 25;
- out.write((char*)t, sizeof(t));
- out.close();
- ifstream in("out.dat", ios::in);
- if (!in)
- {
- cerr << "File open error!";
- return 1;
- }
- vector<test> vt;
- test tmp;
- while (in.read((char*)&tmp, sizeof(test)))
- {
- vt.push_back(tmp);
- if (in == NULL)
- cout << "NULL";
- }
- vector<test>::iterator it;
- for (it=vt.begin(); it!=vt.end(); ++it)
- print_test(*it);
- in.close();
-
- return 0;
- }
复制代码 |
|