HOW TO:讀取二進位檔案 (C++/CLI)

下列程式碼範例會示範從檔案讀取二進位資料。 這裡會使用兩個來自 System.IO 命名空間的類別:FileStreamBinaryReaderFileStream 表示實際的檔案。 BinaryReader 則提供可進行二進位存取的資料流介面。

下列程式碼範例會使用 HOW TO:寫入二進位檔案 (C++/CLI)的程式碼所建立的檔案,檔名為 data.bin。

範例

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

請參閱

其他資源

檔案和資料流 I/O

.NET 程式設計指南