C++读写二进制文件


方法一:

#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

//

  size_t readBinaryFile(const char *filename, unsigned char *&data)
  {
    FILE *fp;
    fopen_s(&fp, filename, "rb");
    if (fp == NULL)
    {
      return 0; //空指针则返回0,文件打开失败
    }
    fseek(fp, 0, SEEK_END);  //将文件指针移动至文件末尾
    size_t size = ftell(fp); //计算文件大小,单位:Byte
    fseek(fp, 0, SEEK_SET);  //把文件指针移回初始位置(文件开头)
    data = (unsigned char *)malloc(sizeof(unsigned char) * size);
    fread(data, size, 1, fp);
    fclose(fp);
    return size;
  }

  size_t readBinaryFile(const char *filename, char *&data)
  {
    FILE *fp;
    fopen_s(&fp, filename, "rb");
    if (fp == NULL)
    {
      return 0; //空指针则返回0,文件打开失败
    }
    fseek(fp, 0, SEEK_END);  //将文件指针移动至文件末尾
    size_t size = ftell(fp); //计算文件大小,单位:Byte
    fseek(fp, 0, SEEK_SET);  //把文件指针移回初始位置(文件开头)
    data = (char *)malloc(sizeof(char) * size);
    fread(data, size, 1, fp);
    fclose(fp);
    return size;
  }

  size_t writeBinaryFile(const char *filename, const unsigned char *data, size_t size)
  {
    FILE *fp;
    fopen_s(&fp, filename, "wb");
    if (fp == NULL)
    {
      return 0;
    }
    size_t written_size = fwrite(data, size, 1, fp);
    fclose(fp);
    return written_size;
  }

  size_t writeBinaryFile(const char *filename, const char *data, size_t size)
  {
    FILE *fp;
    fopen_s(&fp, filename, "wb");
    if (fp == NULL)
    {
      return 0;
    }
    size_t written_size = fwrite(data, size, 1, fp);
    fclose(fp);
    return written_size;
  }


方法二:

#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

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

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


//

posted @ 2022-12-05 16:30  ParamousGIS  阅读(361)  评论(0编辑  收藏  举报