2013年6月23日日曜日

FileStream クラスを使う:CLR

FileStream クラス

// CLRconsole.cpp : メイン プロジェクト ファイルです。

#include "stdafx.h"

using namespace System;
using namespace System::IO;
using namespace System::Text;

void AddText( FileStream^ fs, String^ value )
{
 array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
 fs->Write( info, 0, info->Length );
}

int main(array<System::String ^> ^args)
{
 String^ path = "D:\\Test.txt";

 // Delete the file if it exists.
 // ファイルが存在する場合は削除
 if ( File::Exists( path ) )
 {
  File::Delete( path );
 }

 //Create the file.
 //ファイルを作成します。
 {
  FileStream^ fs = File::Create( path );
  try
  {
   AddText( fs, "This is some text" );
   AddText( fs, "This is some more text," );
   AddText( fs, "\r\nand this is on a new line" );
   AddText( fs, "\r\n\r\nThe following is a subset of characters:\r\n" );
   for ( int i = 1; i < 120; i++ )
   {
    AddText( fs, Convert::ToChar( i ).ToString() );

    //Split the output at every 10th character.
    //10番目の文字ごと改行を入れる
    if ( Math::IEEERemainder( Convert::ToDouble( i ), 10 ) == 0 )
    {
     AddText( fs, "\r\n" );
    }
   }
  }
  finally
  {
   if ( fs )
    delete (IDisposable^)fs;
  }
 }

 //Open the stream and read it back.
 //ストリームをオープンし、それを読み込んで表示。
 {
  FileStream^ fs = File::OpenRead( path );
  try
  {
   array<Byte>^b = gcnew array<Byte>(1024);
   UTF8Encoding^ temp = gcnew UTF8Encoding( true );
   while ( fs->Read( b, 0, b->Length ) > 0 )
   {
    Console::WriteLine( temp->GetString( b ) );
   }
  }
  finally
  {
   if ( fs )
    delete (IDisposable^)fs;
  }
 }

 MessageBox(0, L"OK!", L"test", MB_OK);
}


たぶん、コマンドプロンプトのコードページがShift-JISなので文字化けしている。

0 件のコメント:

コメントを投稿