C++二进制文件的读写

二进制文件的读取:

void readBinareFile(const std::string& filePath, std::vector<uint8_t>& data) {
  std::ifstream ifs(filePath, std::ios::binary);
  if (!ifs) {
    SPDLOG_ERROR("failed to open read file: {}", filePath);
    return;
  }

  // file size
  ifs.seekg(0, std::ios::end);
  std::streamsize size = ifs.tellg();
  ifs.seekg(0, std::ios::beg);

  data.resize(size);
  ifs.read(reinterpret_cast<char*>(data.data()), size);
  ifs.close();
}

二进制文件的写入:

void writeBinareFileOnce(const std::string& filePath, char* buffer, size_t size) {
  std::ofstream ofs(filePath, std::ios::binary);
  if (!ofs) {
    SPDLOG_ERROR("failed to open write file: {}", filePath);
    return;
  }

  ofs.write(buffer, size);
  ofs.close();
}

实际操作中发现,较大文件分块写入的效率要高于一次性整体写入:

void writeBinareFile(const std::string& filePath, char* buffer, size_t size) {
  std::ofstream ofs(filePath, std::ios::binary);
  if (!ofs) {
    SPDLOG_ERROR("failed to open write file: {}", filePath);
    return;
  }

  size_t chunkSize = 32 * 1024;
  size_t offset = 0;
  while (offset < size) {
    size_t size_to_write = std::min(chunkSize, size - offset);
    ofs.write(buffer + offset, size_to_write);
    offset += size_to_write;
  }
  ofs.close();
  return;
}
posted @   卡尔的思索  阅读(141)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
点击右上角即可分享
微信分享提示