Share via


方法 : バイナリ ファイルを読み込む

更新 : 2007 年 11 月

バイナリ データをファイルから読む込む方法を次のコード例に示します。System.IO 名前空間の 2 つのクラス、FileStreamBinaryReader が使用されます。FileStream は実際のファイルを表し、BinaryReader はバイナリへのアクセスを可能にするストリームへのインターフェイスを提供します。

次のコード例では、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;
}

参照

その他の技術情報

ファイルおよびストリーム入出力

.NET プログラミング ガイド