テキストファイル読み込み用クラス

これまでC# で作成してきた「SourceToHTML」を、VC++.NET に焼きなおしてみます。

Reader.h


#pragma once

namespace SourceToHtml
{
using namespace System;
//*******************************************************************************************************
// テキストファイル 読み込み用クラス
//*******************************************************************************************************
public __gc class Reader
{
private:
const Char EOF; // '\0'
const Char NEWLINE; // '\n'

System::IO::StreamReader* textReader;
bool IsOpen;
String* fileName;
String* readBuffer;
int readIndex;
bool FileExists;

// ファイルのCLOSE
void Close();
public:
// 初期化
Reader(String* fileName);
// 終了
~Reader();
// 入力ファイルから1文字ずつ読む
Char getChar();
};
}

Reader.cpp


#include "StdAfx.h"
#include ".\reader.h"

namespace SourceToHtml
{
//*******************************************************************************************************
// テキストファイル 読み込み用クラス
//*******************************************************************************************************
//-------------------------------------------------------------------------------------------------------
// 初期化
//-------------------------------------------------------------------------------------------------------
Reader::Reader(String* fileName):EOF('\0'), NEWLINE('\n')
{
IsOpen = false;
readBuffer = S"";
readIndex = -1;
FileExists = true;

this->fileName = fileName;
}
//-------------------------------------------------------------------------------------------------------
// 終了
//-------------------------------------------------------------------------------------------------------
Reader::~Reader()
{
Close();
}
//-------------------------------------------------------------------------------------------------------
// ファイルのCLOSE
//-------------------------------------------------------------------------------------------------------
void Reader::Close()
{
//OPENしてたら
if (IsOpen)
{
//CLOSEする
textReader->Close();
textReader = NULL;
IsOpen = false;
}
}
//-------------------------------------------------------------------------------------------------------
// 入力ファイルから1文字ずつ読む
//-------------------------------------------------------------------------------------------------------
Char Reader::getChar()
{
//ファイルがなければ、EOFを返す
if (!FileExists) return EOF;

//まだOPENしてなかったら
if (!IsOpen)
{
//ファイルがあれば
if (System::IO::File::Exists(fileName))
{
//OPENする
textReader = new System::IO::StreamReader(fileName, System::Text::Encoding::GetEncoding("Shift_JIS"));
IsOpen = true;
}
else
{
//ファイルがなければ、EOFを返す
FileExists = false;
return EOF;
}
}

//現在位置が初期化されていたら (読み込み用バッファが空っぽ)
if (readIndex < 0)
{
//次の行を読む
readBuffer = textReader->ReadLine();

//次の行がなければ
if (readBuffer == NULL) return EOF;

//現在位置を行の先頭に位置づける
readIndex = 0;
}

//現在位置が読み込み用バッファの最後に達したら
if (readIndex >= readBuffer->Length)
{
//現在位置を初期化する
readIndex = -1;
//改行コードを返す
return NEWLINE;
}

//読み込み用バッファから1文字返し、現在位置を1つ進める
return readBuffer->Chars[readIndex++];
}
}