計算機科学のブログ

reading and writing files - System IO, StreamWriter, StreamReader

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 10(reading and writing files - Save the last byte for me!)、p.539(Pool Puzzle)の解答を求めてみる。

コード

Program.cs

using System;
using System.IO;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            const string d = "delivery.txt";
            StreamWriter o = new StreamWriter("order.txt");
            var pz = new Pizza(new StreamWriter(d, true));
            pz.Idaho(Fargo.Flamingo);
            for (int w = 3; w >= 0; w--)
            {
                var i = new Pizza(new StreamWriter(d, false));
                i.Idaho((Fargo)w);
                Party p = new Party(new StreamReader(d));
                p.HowMuch(o);
            }
            o.WriteLine("That's all folks!");
            o.Close();
        }
    }
}

コード

Pineapple.cs

using System;
namespace MyConsoleApp
{
    public class Pineapple
    {
        public Pineapple()
        {
        }
    }
}

コード

Pizza.cs

using System;
using System.IO;
namespace MyConsoleApp
{
    public class Pizza
    {
        private StreamWriter writer;
        public Pizza(StreamWriter writer)
        {
            this.writer = writer;
        }
        public void Idaho(Fargo f)
        {
            writer.WriteLine(f);
            writer.Close();
        }
    }
}

コード

Party.cs

using System;
using System.IO;

namespace MyConsoleApp
{
    public class Party
    {
        private StreamReader reader;
        public Party(StreamReader reader)
        {
            this.reader = reader;
        }
        public void HowMuch(StreamWriter q)
        {
            q.WriteLine(reader.ReadLine());
            reader.Close();
        }
    }
}

入出力結果(Terminal, Zsh)

% cat ~/Projects/MyConsoleApp/MyConsoleApp/bin/Debug/net5.0/order.txt
West
East
South
North
That's all folks!
% cat ~/Projects/MyConsoleApp/MyConsoleApp/bin/Debug/net5.0/delivery.txt
North
%