다음을 통해 공유


파일 처리 및 I/O(C++/CLI)

.NET Framework를 사용하는 다양한 파일 작업을 보여 줍니다.

다음 항목에서는 네임스페이스에 정의된 클래스를 System.IO 사용하여 다양한 파일 작업을 수행하는 방법을 보여 줍니다.

디렉터리의 파일 열거

다음 코드 예제에서는 디렉터리의 파일 목록을 검색하는 방법을 보여 줍니다. 또한 하위 디렉터리가 열거됩니다. 다음 코드 예제에서는 C:\Windows 디렉터리의 내용을 표시 하는 메서드를 GetDirectories 사용 GetFilesGetFiles 합니다.

예시

// enum_files.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main()
{
   String^ folder = "C:\\";
   array<String^>^ dir = Directory::GetDirectories( folder );
   Console::WriteLine("--== Directories inside '{0}' ==--", folder);
   for (int i=0; i<dir->Length; i++)
      Console::WriteLine(dir[i]);

   array<String^>^ file = Directory::GetFiles( folder );
   Console::WriteLine("--== Files inside '{0}' ==--", folder);
   for (int i=0; i<file->Length; i++)
      Console::WriteLine(file[i]);

   return 0;
}

파일 시스템 변경 내용 모니터링

다음 코드 예제에서는 생성, 변경, 삭제 또는 이름이 바뀐 파일에 해당하는 이벤트를 등록하는 데 사용합니다 FileSystemWatcher . 파일에 대한 변경 내용에 대해 디렉터리를 주기적으로 폴링하는 대신, 변경 내용이 검색될 때 클래스를 사용하여 FileSystemWatcher 이벤트를 발생하도록 할 수 있습니다.

예시

// monitor_fs.cpp
// compile with: /clr
#using <system.dll>

using namespace System;
using namespace System::IO;

ref class FSEventHandler
{
public:
    void OnChanged (Object^ source, FileSystemEventArgs^ e)
    {
        Console::WriteLine("File: {0} {1}",
               e->FullPath, e->ChangeType);
    }
    void OnRenamed(Object^ source, RenamedEventArgs^ e)
    {
        Console::WriteLine("File: {0} renamed to {1}",
                e->OldFullPath, e->FullPath);
    }
};

int main()
{
   array<String^>^ args = Environment::GetCommandLineArgs();

   if(args->Length < 2)
   {
      Console::WriteLine("Usage: Watcher.exe <directory>");
      return -1;
   }

   FileSystemWatcher^ fsWatcher = gcnew FileSystemWatcher( );
   fsWatcher->Path = args[1];
   fsWatcher->NotifyFilter = static_cast<NotifyFilters>
              (NotifyFilters::FileName |
               NotifyFilters::Attributes |
               NotifyFilters::LastAccess |
               NotifyFilters::LastWrite |
               NotifyFilters::Security |
               NotifyFilters::Size );

    FSEventHandler^ handler = gcnew FSEventHandler();
    fsWatcher->Changed += gcnew FileSystemEventHandler(
            handler, &FSEventHandler::OnChanged);
    fsWatcher->Created += gcnew FileSystemEventHandler(
            handler, &FSEventHandler::OnChanged);
    fsWatcher->Deleted += gcnew FileSystemEventHandler(
            handler, &FSEventHandler::OnChanged);
    fsWatcher->Renamed += gcnew RenamedEventHandler(
            handler, &FSEventHandler::OnRenamed);

    fsWatcher->EnableRaisingEvents = true;

    Console::WriteLine("Press Enter to quit the sample.");
    Console::ReadLine( );
}

이진 파일 읽기

다음 코드 예제에서는 네임스페이스에서 두 개의 클래스를 사용하여 파일에서 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;
}

텍스트 파일 읽기

다음 코드 예제에서는 네임스페이스에 정의된 System.IO 클래스를 사용하여 StreamReader 한 번에 한 줄씩 텍스트 파일을 열고 읽는 방법을 보여 줍니다. 이 클래스의 인스턴스는 텍스트 파일을 여는 데 사용되며 이 System.IO.StreamReader.ReadLine 메서드는 각 줄을 검색하는 데 사용됩니다.

이 코드 예제에서는 textfile.txt라는 이름의 파일을 읽고 텍스트를 포함합니다. 이러한 종류의 파일에 대한 자세한 내용은 방법: 텍스트 파일 작성(C++/CLI)을 참조하세요.

예시

// text_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "textfile.txt";
   try
   {
      Console::WriteLine("trying to open file {0}...", fileName);
      StreamReader^ din = File::OpenText(fileName);

      String^ str;
      int count = 0;
      while ((str = din->ReadLine()) != nullptr)
      {
         count++;
         Console::WriteLine("line {0}: {1}", count, str );
      }
   }
   catch (Exception^ e)
   {
      if (dynamic_cast<FileNotFoundException^>(e))
         Console::WriteLine("file '{0}' not found", fileName);
      else
         Console::WriteLine("problem reading file '{0}'", fileName);
   }

   return 0;
}

파일 정보 검색

다음 코드 예제에서는 클래스를 FileInfo 보여 줍니다. 파일 이름이 있는 경우 이 클래스를 사용하여 파일 크기, 디렉터리, 전체 이름, 생성 날짜 및 시간 및 마지막 수정 시간과 같은 파일에 대한 정보를 검색할 수 있습니다.

이 코드는 메모장.exe에 대한 파일 정보를 검색합니다.

예시

// file_info.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main()
{
   array<String^>^ args = Environment::GetCommandLineArgs();
   if (args->Length < 2)
   {
      Console::WriteLine("\nUSAGE : file_info <filename>\n\n");
      return -1;
   }

   FileInfo^ fi = gcnew FileInfo( args[1] );

   Console::WriteLine("file size: {0}", fi->Length );

   Console::Write("File creation date:  ");
   Console::Write(fi->CreationTime.Month.ToString());
   Console::Write(".{0}", fi->CreationTime.Day.ToString());
   Console::WriteLine(".{0}", fi->CreationTime.Year.ToString());

   Console::Write("Last access date:  ");
   Console::Write(fi->LastAccessTime.Month.ToString());
   Console::Write(".{0}", fi->LastAccessTime.Day.ToString());
   Console::WriteLine(".{0}", fi->LastAccessTime.Year.ToString());

   return 0;
}

이진 파일 작성

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

다음 코드 예제에서는 정수가 포함된 파일을 이진 형식으로 작성합니다. 이 파일은 방법: 이진 파일 읽기(C++/CLI)의 코드로 읽을 수 있습니다.

예시

// binary_write.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;

int main()
{
   array<Int32>^ data = {1, 2, 3, 10000};

   FileStream^ fs = gcnew FileStream("data.bin", FileMode::Create);
   BinaryWriter^ w = gcnew BinaryWriter(fs);

   try
   {
      Console::WriteLine("writing data to file:");
      for (int i=0; i<data->Length; i++)
      {
         Console::WriteLine(data[i]);
         w->Write(data[i]);
      }
   }
   catch (Exception^)
   {
     Console::WriteLine("data could not be written");
     fs->Close();
     return -1;
   }

   fs->Close();
   return 0;
}

텍스트 파일 작성

다음 코드 예제에서는 네임스페이스에 정의된 System.IO 클래스를 사용하여 StreamWriter 텍스트 파일을 만들고 텍스트 파일을 작성하는 방법을 보여 줍니다. StreamWriter 생성자는 만들 파일의 이름을 사용합니다. 파일이 있으면 덮어씁니다(True를 두 번째 StringWriter 생성자 인수로 전달하지 않는 한).

그런 다음, 파일은 및 WriteLine 함수를 Write 사용하여 제출됩니다.

예시

// text_write.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main()
{
   String^ fileName = "textfile.txt";

   StreamWriter^ sw = gcnew StreamWriter(fileName);
   sw->WriteLine("A text file is born!");
   sw->Write("You can use WriteLine");
   sw->WriteLine("...or just Write");
   sw->WriteLine("and do {0} output too.", "formatted");
   sw->WriteLine("You can also send non-text objects:");
   sw->WriteLine(DateTime::Now);
   sw->Close();
   Console::WriteLine("a new file ('{0}') has been written", fileName);

   return 0;
}

참고 항목

C++/CLI를 사용한 .NET 프로그래밍 (Visual C++)
파일 및 스트림 I/O
System.IO 네임스페이스