Skip to content

Latest commit

 

History

History
62 lines (54 loc) · 1.93 KB

how-to-write-a-binary-file-cpp-cli.md

File metadata and controls

62 lines (54 loc) · 1.93 KB
title ms.custom ms.date ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic dev_langs helpviewer_keywords ms.assetid caps.latest.revision author ms.author manager
How to: Write a Binary File (C++/CLI) | Microsoft Docs
11/04/2016
cpp-windows
article
C++
binary files, writing in C++
files [C++], binary
35d97ee6-fc7e-4c36-be18-8bbb3b44b3ae
10
mikeblome
mblome
ghogen

How to: Write a Binary File (C++/CLI)

The following code example demonstrates writing binary data to a file. Two classes from the xref:System.IO namespace are used: xref:System.IO.FileStream and xref:System.IO.BinaryWriter. xref:System.IO.FileStream represents the actual file, while xref:System.IO.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;  
}  

See Also

File and Stream I-O
.NET Programming with C++/CLI (Visual C++)