計算機科学のブログ

reading and writing files - Save the last byte for me! - StreamWriter, WriteLine method, chain

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (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 ConsoleApp1;

const string d = "delivery.txt";
StreamWriter o = new("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(new StreamReader(d));
    p.HowMuch(o);
}
o.WriteLine("That's all folks!");
o.Close();

// delivery.txt
// North

Fargo.cs

namespace ConsoleApp1;

public enum Fargo
{
    North,
    South,
    East,
    West,
    Flamingo
}

Pizza.cs

namespace ConsoleApp1;

public class Pizza(StreamWriter streamWriter)
{
    private readonly StreamWriter streamWriter = streamWriter;

    public void Idaho(Fargo f)
    {
        streamWriter.WriteLine(f);
        streamWriter.Close();
    }
}

Party.cs

using System;

namespace ConsoleApp1;

public class Party(StreamReader streamReader)
{
    private readonly StreamReader streamReader = streamReader;

    public void HowMuch(StreamWriter streamWriter)
    {
        streamWriter.WriteLine(streamReader.ReadLine());
        streamReader.Close();
    }
}

入出力結果(Terminal, Zsh)

% cat order.txt 
West
East
South
North
That's all folks!
% cat delivery.txt 
North
%