reading and writing files - Save the last byte for me! - binary date, BinaryWriter class
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.569(Sharpen your pencil)の解答を求めてみる。
コード
Program.cs
int intValue = 48769414;
string stringValue = "Hello!";
byte[] bytes = [47, 129, 0, 116];
float floatValue = 491.695F;
char charValue = 'E';
using (var output = File.Create("binarydata.dat"))
using (var writer = new BinaryWriter(output))
{
writer.Write(intValue);
writer.Write(stringValue);
writer.Write(bytes);
writer.Write(floatValue);
writer.Write(charValue);
}
byte[] dataWritten = File.ReadAllBytes("binarydata.dat");
// 86 29 e8 02 06 48 65 6c 6c 6f 21 2f 81 00 74 f6 d8 f5 43 45 - 20 bytes
foreach (byte b in dataWritten)
{
Console.Write("{0:x2} ", b);
}
Console.WriteLine(" - {0} bytes", dataWritten.Length);
入出力結果(Terminal, Zsh)
% dotnet run
86 29 e8 02 06 48 65 6c 6c 6f 21 2f 81 00 74 f6 d8 f5 43 45 - 20 bytes
%