c++数组的二进制文件读写

#include<fstream> //for ifstream、ofstream

template<typename OB>
inline void saveObject(const char*filename, OB & object,int length) //传入要保存的对象引用
{
    std::ofstream osm(filename, std::ios::out | std::ios::binary);
    osm.write((const char *)&object, length*sizeof(OB));
    osm.close();
}

template<typename OB>
inline void readObject(const char* filename, OB * object,int length) //传入读取之后对象存储的指针
{
    std::ifstream ism(filename, std::ios::in | std::ios::binary);
    ism.read((char*)object, length*sizeof(OB));
    ism.close();
}

int main()
{
    uint16_t b[2] = { 1,2 };
    saveObject("Data.bin", b,2);
    uint16_t c[2];
    readObject("Data.bin", c,2);
    return 0;
}

 

【参考】

【C++ 存储和读取二进制文件以及类的实例】_c++ 保存二进制文件_xhgen的博客-CSDN博客

posted @ 2023-10-17 15:24  夕西行  阅读(129)  评论(0编辑  收藏  举报