Práce se soubory a vstupně-výstupní operace (C++/CLI)

Demonstruje různé operace se soubory pomocí rozhraní .NET Framework.

Následující témata ukazují použití tříd definovaných v System.IO oboru názvů k provádění různých operací se soubory.

Vytvoření výčtu souborů v adresáři

Následující příklad kódu ukazuje, jak načíst seznam souborů v adresáři. Kromě toho jsou podadresáře výčty. Následující příklad kódu používá GetFilesGetFiles a GetDirectories metody k zobrazení obsahu adresáře C:\Windows.

Příklad

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

Monitorování změn systému souborů

Následující příklad kódu používá FileSystemWatcher k registraci událostí odpovídajících souborům, které se vytvářejí, mění, odstraňují nebo přejmenovávají. Místo pravidelného dotazování adresáře na změny souborů můžete pomocí FileSystemWatcher třídy aktivovat události při zjištění změny.

Příklad

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

Čtení binárního souboru

Následující příklad kódu ukazuje, jak číst binární data ze souboru pomocí dvou tříd z System.IO oboru názvů: FileStream a BinaryReader. FileStream představuje skutečný soubor. BinaryReader poskytuje rozhraní pro datový proud, který umožňuje binární přístup.

Příklad kódu načte soubor s názvem data.bin a obsahuje celá čísla v binárním formátu. Informace o tomto typu souboru naleznete v tématu Postupy: Zápis binárního souboru (C++/CLI).

Příklad

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

Čtení textového souboru

Následující příklad kódu ukazuje, jak otevřít a číst textový soubor po jednom řádku pomocí StreamReader třídy, která je definována System.IO v oboru názvů. Instance této třídy se používá k otevření textového souboru a pak System.IO.StreamReader.ReadLine se metoda používá k načtení každého řádku.

Tento příklad kódu přečte soubor s názvem textfile.txt a obsahuje text. Informace o tomto typu souboru naleznete v tématu Postupy: Zápis textového souboru (C++/CLI).

Příklad

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

Načtení informací o souboru

Následující příklad kódu ukazuje FileInfo třídu. Pokud máte název souboru, můžete pomocí této třídy načíst informace o souboru, jako je například velikost souboru, adresář, úplný název a datum a čas vytvoření a poslední změny.

Tento kód načte informace o souboru pro Poznámkový blok.exe.

Příklad

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

Zápis binárního souboru

Následující příklad kódu ukazuje zápis binárních dat do souboru. Používá třídy System.IO a FileStream z oboru názvů BinaryWriter. FileStream představuje skutečný soubor, zatímco BinaryWriter poskytuje rozhraní streamu, který umožňuje binární přístup.

Následující příklad kódu zapíše soubor obsahující celá čísla v binárním formátu. Tento soubor lze číst pomocí kódu v části Postupy: Čtení binárního souboru (C++/CLI).

Příklad

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

Zápis textového souboru

Následující příklad kódu ukazuje, jak vytvořit textový soubor a zapsat do něj text pomocí StreamWriter třídy, která je definována System.IO v oboru názvů. Konstruktor StreamWriter přebírá název souboru, který se má vytvořit. Pokud soubor existuje, přepíše se (pokud nepředáte hodnotu True jako druhý StringWriter argument konstruktoru).

Soubor se pak zasadí pomocí Write funkcí a WriteLine funkcí.

Příklad

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

Viz také

Programování pro .NET v jazyce C++/CLI (Visual C++)
Vstup/výstup souborů a streamů
System.IO obor názvů