开发者

C++ BinaryReader and BinaryWriter

开发者 https://www.devze.com 2023-01-26 19:34 出处:网络
I need to write an array of int to an output file as binary and also read the binary data as int in the programme in C++ Linux, something like the Bina开发者_运维百科ryReader and BinaryWriter in C#. H

I need to write an array of int to an output file as binary and also read the binary data as int in the programme in C++ Linux, something like the Bina开发者_运维百科ryReader and BinaryWriter in C#. How could I do that?

Thanks


Barring some outstanding reason to do otherwise, you'd typically use std::ostream::write and std::istream::read. Since you're producing a binary stream, you'll also typically want to specify std::ios::binary when you open the file.


Just to flesh out Jerry and J-16 SDiZ's suggestions:

std::ofstream file(filename, ios::binary);
myFile.write (static_cast<const char*>(&x), sizeof x);
...
file.read(static_cast<char *>(x), sizeof x);

Further, you may want to consider putting the data in network byte-order if you need more portability: see the man-page (or equivalent) for ntohl et al on your system.


cast the array of int to (char*) and use istream::read / ostream::write ?


here is some code you might find useful:

bool readBinVector(const std::string &fname, std::vector<double> &val) {
  long N;
  std::fstream in(fname.c_str(), std::ios_base::binary | std::ios_base::in | std::ios::ate);

  if(!in.is_open()) {
    std::cout << "Error opening the file\n" << fname << "\n" << std::endl;
    return false;
  }

  N = in.tellg()/(8);

  val.resize(N);

  in.seekg(0,std::ios::beg); // begeinning of file

  in.read((char*)&val[0], N*sizeof(double));

  in.close();
  return true;
}

bool writeBinVector(const std::string &fname, const std::vector<double> &val) {
  std::ofstream outfile (fname.c_str(),std::ofstream::binary);
  outfile.write((char*)&val[0],val.size()*8);
  outfile.close();
  return true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消