Pages

System::IO

To access a file it is possible to use the System::IO::FileStream that provides access to the low level details of a file.

As example, we write a function, readFile(), that access a file and put its content in a managed array:

void readFile(System::String^ filename)
{
using System::IO::FileStream;
using System::IO::FileMode;

FileStream^ fs = gcnew FileStream(filename, FileMode::Open); // 1.

long long len = fs->Length;

System::Console::WriteLine("File length is {0}", len);

int size = static_cast(len); // 2.
array^ content = gcnew array(size);
fs->Read(content, 0, size);
fs->Close();
}

1. since we specify the mode FileMode::Open, if the file does not exists, an exception is thrown.
2. the length of a FileStream is defined as a long long, but the size of an array in just an int. Instead of simply casting to int, as we did here, we should add a bit of logic, to properly read all the file.

If we expect the file to be a text one, we could use StreamReader and TextWriter:

void readTextFile(System::String^ filename)
{
using System::IO::StreamReader;
using System::IO::TextWriter;

StreamReader^ sr = gcnew StreamReader(filename);
TextWriter^ tw = System::Console::Out;
tw->WriteLine("File {0}:", filename);

System::String^ line;
for(int i = 0; (line = sr->ReadLine()) != nullptr; ++i)
tw->WriteLine("Line {0}: {1}", i, line);

sr->Close();
}

This post is based on my reading on the book "Expert C++/CLI: .NET for Visual C++ Programmers" by Marcus Heege, APress.

No comments:

Post a Comment