2012年4月24日火曜日

開発環境

  • Microsoft Windows 7 Home Premium (OS)
  • Microsoft Visual C# 2010 Express Edition (IDE)
  • 言語: C#

独習C# 第3版 ハーバート・シルト (著) エディフィストラーニング株式会社 矢嶋聡 (監修, 翻訳) の第11章(CI/O処理)の理解度チェック9を解いてみる。

9.

コード

using System;
using System.IO;

class Tester
{
    public void Run()
    {
        try
        {
            int n;
            Console.WriteLine("既存のファイル名を入力");
            string name1 = Console.ReadLine();
            Console.WriteLine("変換後のファイル名を入力");
            string name2 = Console.ReadLine();
            FileStream fi = new FileStream(name1, FileMode.Open);
            FileStream fo = new FileStream(name2, FileMode.CreateNew);
            do
            {
                n = fi.ReadByte();
                if ((char)n == ' ')
                {
                    n = '-';
                }
                if (n != -1)
                {
                    fo.WriteByte((byte)n);
                }
            } while (n != -1);
            fi.Close();
            fo.Close();
        }
        catch (IOException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine("終了");
        }
    }
    static void Main()
    {
        Tester t = new Tester();
        t.Run();
    }
}

入出力結果(Console Window)

既存のファイル名を入力
sample.txt
変換後のファイル名を入力
copy.txt
終了
続行するには何かキーを押してください . . .

テキストファイル

sample.txt

C# JavaScript Perl
     Ruby    Python
  PHP

copy.txt

C#-JavaScript-Perl
-----Ruby----Python
--PHP

0 コメント:

コメントを投稿