2012年6月24日日曜日

C++/CLI テキストの置換

main.cpp

using namespace System;

// テキストファイルを開いて文字列置換を行うテスト
void ReplaceText(String^ path, String^ strOld, String^ strNew)
{
  if (!IO::File::Exists(path)) return;

  Text::Encoding^ enc = Text::Encoding::GetEncoding("shift_jis");

  // テキストファイルの読み込み
  IO::StreamReader^ sr = gcnew IO::StreamReader(path, enc);
  String^ textInput = sr->ReadToEnd();
  sr->Close();

  // 置換する
  String^ textOutput = textInput->Replace(strOld, strNew);

  // テキストファイルの書き込み
  IO::StreamWriter^ sw = gcnew IO::StreamWriter(path, false, enc);
  sw->Write(textOutput);
  sw->Close();
}

int main(array ^args)
{
  if(args->Length == 3) {
    ReplaceText(args[0], args[1], args[2]);
  }
    return 0;
}