-
二进制文件速度快,空间效率高
-
写入数据到二进制文件
#include<iostream>
#include<fstream>
using namespace std;
int main()
{// 定义一个结构体struct student{int id; // 学号char name[20]; // 姓名double score; // 成绩} s1 = {1001, "张三", 90.5}, s2 = {1002, "李四", 80.5};// 将结构体写入二进制文件ofstream fout("student.dat", ios::binary);if (fout){fout.write((char*)&s1, sizeof(student));fout.write((char*)&s2, sizeof(student));fout.close();}return 0;
}
-
从二进制文件读取数据
#include<iostream>
#include<fstream>
using namespace std;
int main()
{// 定义一个结构体struct student{int id; // 学号char name[20]; // 姓名double score; // 成绩} s;// 从二进制文件中读取结构体数据ifstream fin("student.dat", ios::binary);if (fin){fin.read((char*)&s, sizeof(student));while (!fin.eof()){cout<< "学号:" << s.id<< ",姓名:" << s.name<< ",成绩:" << s.score<< endl;fin.read((char*)&s, sizeof(student));}fin.close();}return 0;
}
注意 结构体必须一致且写入顺序与读取顺序一致
-
保存vector数据
#include<iostream>
#include<fstream>
#include "Eigen/Core"
using namespace std;int main()
{ofstream fout("test.dat", ios::binary | ios::app | ios::out);vector<Eigen::Vector3f> points;points.resize(100);/** save data*/int num = points.size();fout.write(reinterpret_cast<char*>(&num), sizeof(num));fout.write(reinterpret_cast<char*>(&points[0]), num*sizeof(points[0]));char type[10];string str = "senr";strncpy(type, str.c_str(), sizeof(type));fout.write(reinterpret_cast<char*>(&type), 10);fout.close();return 0;
}
-
读取vector数据
#include<iostream>
#include<fstream>
#include "Eigen/Core"
using namespace std;int main()
{ifstream fin("test.dat", ios::binary | ios::in);vector<Eigen::Vector3f> points;int num = 0;fin.read(reinterpret_cast<char*>(&num), sizeof(int));points.resize(num);fin.read(reinterpret_cast<char*>(&points[0]), num*sizeof(points[0]));char type[10];fin.read(reinterpret_cast<char*>(&type), 10);string str(type);fin.close();return 0;
}
对于不定长的数组,需要存储数据的长度信息,然后获取数据。