Práce se soubory a vstupně-výstupní operace (C++/CLI)
Ukazuje různé operace se soubory pomocí .NET Framework.
Následující témata ukazují použití tříd definovaných v oboru názvů System.IO k provádění různých operací se soubory.
Zobrazení 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 v podadresářích výčty. následující příklad kódu používá metody getfilesagetdirectors 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;
}
Monitorovat změny systému souborů
Následující příklad kódu používá FileSystemWatcher k registraci událostí odpovídajících souborům, které jsou vytvářeny, měněny, smazány nebo přejmenovány. Místo pravidelného dotazování adresáře na změny souborů můžete použít třídu FileSystemWatcher k vyvolání událostí 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 oboru názvů System.IO : 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 přeč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 How to: Write a Binary File (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;
}
Číst textový soubor
Následující příklad kódu ukazuje, jak otevřít a číst textový soubor po jednom řádku pomocí třídy StreamReader , která je definována v oboru názvů System.IO . Instance této třídy slouží k otevření textového souboru a poté je použita metoda System. IO. StreamReader. ReadLine 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 How to: Write a text File (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číst informace o souboru
Následující příklad kódu ukazuje třídu FileInfo . Pokud máte název souboru, můžete tuto třídu použít k načtení informací o souboru, jako je například velikost souboru, adresář, celé jméno a datum a čas vytvoření a Poslední změna.
Tento kód načte informace o souboru pro Notepad.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žívají se dvě třídy z oboru názvů System.IO : FileStream a BinaryWriter. FileStream představuje skutečný soubor, zatímco BinaryWriter poskytuje rozhraní pro datový proud, který umožňuje binární přístup.
Následující příklad kódu zapisuje soubor obsahující celá čísla v binárním formátu. Tento soubor lze číst pomocí kódu v tématu 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;
}
Zapsat textový soubor
Následující příklad kódu ukazuje, jak vytvořit textový soubor a zapsat do něj text pomocí třídy StreamWriter , která je definována v oboru názvů System.IO . Konstruktor StreamWriter přebírá název souboru, který se má vytvořit. Pokud soubor existuje, bude přepsán (pokud nepředáte hodnotu true jako druhý argument konstruktoru StringWriter ).
Soubor je pak uložen pomocí funkcí Write a WriteLine .
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++)
Vstupně-výstupní operace se soubory a datovým proudem
Obor názvů System.IO