二进制输出文件

流最初专为文本设计,因此默认输出模式为文本。 在文本模式下,换行符展开为回车换行对。 扩展可能会引发如下所示的问题:

// 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 );
}

另请参阅

输出流