-
二進制文件速度快,空間效率高
-
寫入數據到二進制文件
#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;
}
對于不定長的數組,需要存儲數據的長度信息,然后獲取數據。