Skip to content

Latest commit

 

History

History
60 lines (53 loc) · 2.07 KB

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

File metadata and controls

60 lines (53 loc) · 2.07 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: Read a Binary File (C++/CLI) | Microsoft Docs
11/04/2016
cpp-windows
article
C++
files [C++], binary
binary files, reading in C++
41ad9ad1-5cac-489c-874e-4bb3a649073a
13
mikeblome
mblome
ghogen

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

The following code example shows how to read binary data from a file, by using two classes from the xref:System.IO?displayProperty=fullName namespace: xref:System.IO.FileStream and xref:System.IO.BinaryReader. xref:System.IO.FileStream represents the actual file. xref:System.IO.BinaryReader provides an interface to the stream that allows binary access.

The code example reads a file that's named data.bin and contains integers in binary format. For information about this kind of file, see How to: Write a Binary File (C++/CLI).

Example

// binary_read.cpp  
// compile with: /clr  
#using<system.dll>  
using namespace System;  
using namespace System::IO;  
  
int main()   
{  
   String^ fileName = "data.bin";  
   try  
   {  
      FileStream^ fs = gcnew FileStream(fileName, FileMode::Open);  
      BinaryReader^ br = gcnew BinaryReader(fs);  
  
      Console::WriteLine("contents of {0}:", fileName);  
      while (br->BaseStream->Position < br->BaseStream->Length)  
         Console::WriteLine(br->ReadInt32().ToString());  
  
      fs->Close( );  
   }  
   catch (Exception^ e)  
   {  
      if (dynamic_cast<FileNotFoundException^>(e))  
         Console::WriteLine("File '{0}' not found", fileName);  
      else  
         Console::WriteLine("Exception: ({0})", e);  
      return -1;  
   }  
   return 0;  
}  

See Also

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