本帖最后由 superbe 于 2020-7-24 18:34 编辑
name成员如果是char数组比较容易处理,但如果是string用二进制来处理就比较麻烦,因为string实际上并没有包含字符串本身,而是字符串的地址。一个思路是,保存string的字符串长度和字符串内容,读取时先读长度再按长度读字符串到string。
下面是测试代码:#include <iostream>
#include <string >
#include <fstream>
using namespace std;
struct Student
{
string name;
int num;
int age;
char sex;
};
int main()
{
Student s1[3] = {
{"zhangsan", 1, 20, 'M'},
{"lisi", 2, 21, 'F'},
{"wangwu", 3, 22, 'M'} };
//写入文件
ofstream outfile("stud.dat", ios::binary);
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
for (int i = 0; i < 3; i++) {
size_t sz = s1[i].name.size();
outfile.write((char *)&sz, sizeof(size_t)); //保存name字符串长度
outfile.write(s1[i].name.c_str(), sz); //保存name字符串
outfile.write((char *)&s1[i].num, sizeof(int));
outfile.write((char *)&s1[i].age, sizeof(int));
outfile.write((char *)&s1[i].sex, sizeof(char));
}
outfile.close();
//读出文件
ifstream infile("stud.dat", ios::binary);
if (!infile){
cerr << "open error!" << endl;
exit(1);
}
Student s2[3];
for (int i = 0; i < 3; i++) {
size_t sz;
infile.read((char *)&sz, sizeof(size_t));
s2[i].name.resize(sz);
infile.read((char *)s2[i].name.data(), sz);
infile.read((char *)&s2[i].num, sizeof(int));
infile.read((char *)&s2[i].age, sizeof(int));
infile.read((char *)&s2[i].sex, sizeof(char));
}
infile.close();
for (int i = 0; i<3; i++) {
cout << "#" << i + 1 << ": ";
cout << s2[i].age << " "
<< s2[i].name << " "
<< s2[i].num << " "
<< s2[i].sex << endl;
}
return 0;
}
运行结果:
#1: 20 zhangsan 1 M
#2: 21 lisi 2 F
#3: 22 wangwu 3 M
请按任意键继续. . .
|