intの配列をバイナリとして出力ファイルに書き込む必要があります。また、C++のBinaryReaderやBinaryWriterのようなプログラムでintとしてバイナリデータを読み取る必要があります。どうすればいい?それ以外の場合は行うには、いくつかの優秀な理由がなければC++ BinaryReaderとBinaryWriter
おかげ
intの配列をバイナリとして出力ファイルに書き込む必要があります。また、C++のBinaryReaderやBinaryWriterのようなプログラムでintとしてバイナリデータを読み取る必要があります。どうすればいい?それ以外の場合は行うには、いくつかの優秀な理由がなければC++ BinaryReaderとBinaryWriter
おかげ
は、あなたが一般的にstd::ostream::write
とstd::istream::read
を使用すると思います。バイナリストリームを生成しているので、通常はファイルを開くときにstd::ios::binary
と指定します。
int
から(char*)
の配列をキャストし、istream::read
/ostream::write
を使用しますか?
だけジェリーとJ-16 SDiZの提案肉付けする:さらに
std::ofstream file(filename, ios::binary);
myFile.write (static_cast<const char*>(&x), sizeof x);
...
file.read(static_cast<char *>(x), sizeof x);
を、あなたはより多くの移植が必要な場合は、ネットワークバイト順にデータを置くことを検討する必要があります。(男性・ページを参照してくださいまたはそれと同等のもの)を使用してください。ここ
はあなたが役立つかもしれないいくつかのコードです:
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;
}
ここでは役に立つかもしれませんな答えだ: http://stackoverflow.com/questions/14077781/id-like-to-use- if -stream-in-c-to-mimic-cs-binaryreader-binary – KBog