How to: Write a Binary File (C++/CLI)
The following code example demonstrates writing binary data to a file. Two classes from the System.IO namespace are used: FileStream and BinaryWriter. FileStream represents the actual file, while BinaryWriter provides an interface to the stream that allows binary access.
The following code example writes a file containing integers in binary format. This file can be read with the code in How to: Read a Binary File (C++/CLI).
Example
// binary_write.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;
int main()
{
array<Int32>^ data = {1, 2, 3, 10000};
FileStream^ fs = gcnew FileStream("data.bin", FileMode::Create);
BinaryWriter^ w = gcnew BinaryWriter(fs);
try
{
Console::WriteLine("writing data to file:");
for (int i=0; i<data->Length; i++)
{
Console::WriteLine(data[i]);
w->Write(data[i]);
}
}
catch (Exception^)
{
Console::WriteLine("data could not be written");
fs->Close();
return -1;
}
fs->Close();
return 0;
}