2010-11-22 20 views
1

intの配列をバイナリとして出力ファイルに書き込む必要があります。また、C++のBinaryReaderやBinaryWriterのようなプログラムでintとしてバイナリデータを読み取る必要があります。どうすればいい?それ以外の場合は行うには、いくつかの優秀な理由がなければC++ BinaryReaderとBinaryWriter

おかげ

+0

ここでは役に立つかもしれませんな答えだ: http://stackoverflow.com/questions/14077781/id-like-to-use- if -stream-in-c-to-mimic-cs-binaryreader-binary – KBog

答えて

3

は、あなたが一般的にstd::ostream::writestd::istream::readを使用すると思います。バイナリストリームを生成しているので、通常はファイルを開くときにstd::ios::binaryと指定します。

0

intから(char*)の配列をキャストし、istream::read/ostream::writeを使用しますか?

1

だけジェリーと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); 

を、あなたはより多くの移植が必要な場合は、ネットワークバイト順にデータを置くことを検討する必要があります。(男性・ページを参照してくださいまたはそれと同等のもの)を使用してください。ここ

0

はあなたが役立つかもしれないいくつかのコードです:

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; 
} 
関連する問題