다음을 통해 공유


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

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

이 코드 예제에서는 이름이 data.bin이고 이진 형식의 정수를 포함하는 파일을 읽습니다. 이런 종류의 파일에 대한 자세한 내용은 방법: 이진 파일 쓰기(C++/CLI)를 참조하십시오.

예제

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

Visual C++의 .NET 프로그래밍