C++写入和读取结构体到二进制文件

本文介绍了如何在C++中使用二进制文件高效地保存和读取结构体数据,以及处理不定长数组的技巧,重点展示了如何用`ofstream`和`ifstream`操作`student`和`Eigen::Vector3f`类型的vector数据。
  • 二进制文件速度快,空间效率高

  • 写入数据到二进制文件

#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*)&amp;s1, sizeof(student));
        fout.write((char*)&amp;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;
}

对于不定长的数组,需要存储数据的长度信息,然后获取数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值