Skip to content

Visual Studio С++ чтение файла

by admin on September 27th, 2011

Функции работы с файлами и операции ввода-вывода (C++/CLI)

http://msdn.microsoft.com/ru-ru/library/d3ccyysc.aspx

учимся читать msdn

Перечисление файлов в каталоге

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

Чтение данных из двоичного файла

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

Запись в двоичный файл

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

Чтение из текстового файла (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;
}

Запись данных в текстовый файл

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

Перечисление файлов в каталоге

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

Отслеживание изменений в файловой системе

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

Получение сведений о файле

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


From → Files

Comments are closed.