次の方法で共有


バイナリ出力ファイル

ストリームは本来、テキスト向けとして設計されており、既定の出力モードはテキストです。 テキスト モードでは、ラインフィード (改行) 文字が復帰と改行のペアに拡張されます。 この拡大は次のような問題を起こす可能性があります。

// binary_output_files.cpp
// compile with: /EHsc
#include <fstream>
using namespace std;
int iarray[2] = { 99, 10 };
int main( )
{
    ofstream os( "test.dat" );
    os.write( (char *) iarray, sizeof( iarray ) );
}

このプログラムでは、{ 99, 0, 10, 0 } というバイト シーケンスの出力を想定していたところ、{ 99, 0, 13, 10, 0 } が出力されます。バイナリ入力を要求するプログラムで問題が起こります。 文字が変換なしで書き込まれる、本来のバイナリ出力が必要であれば、ofstream コンストラクター openmode 引数を利用し、バイナリ出力を指定できます。

// binary_output_files2.cpp
// compile with: /EHsc
#include <fstream>
using namespace std;
int iarray[2] = { 99, 10 };

int main()
{
   ofstream ofs ( "test.dat", ios_base::binary );

   // Exactly 8 bytes written
   ofs.write( (char*)&iarray[0], sizeof(int)*2 );
}

関連項目

出力ストリーム