다음을 통해 공유


방법: 이진 파일 읽기(C++/CLI)

다음 코드 예제에서는 파일의 이진 데이터를 읽는 방법을 보여 줍니다. System.IO 네임스페이스의 두 클래스인 FileStreamBinaryReader가 사용됩니다. FileStream은 실제 파일을 나타내고 BinaryReader는 이진 액세스를 허용하는 인터페이스를 스트림에 제공합니다.

다음 코드 예제에서는 방법: 이진 파일 쓰기(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 프로그래밍 가이드