lispとrubyとpythonと その8 ファイルIO(ruby)

Rubyではこんな感じ。
pack、unpackがよく分からない。perlな人には馴染み深いのかなぁ。

# -*- coding: utf-8 -*-

#テキストファイル書き込み
def f0()
  f = File.open("./test.txt","a")
  begin
    f.write "hello world\n"
  ensure
    f.close
  end
end

#テキストファイル読み込み
def f1()
  f = File.open("./test.txt", "r")
  begin
    puts f.gets until f.eof?
  ensure
    f.close
  end
end

f0()
f1()
#->hello world

#普通はこう
def f2()
  File.open("./test2.txt","w") do |f|
    f.write "hello world2\n"
  end
  
  File.open("./test2.txt","r") do |f|
    puts f.gets until f.eof?
  end
end

f2()
#->hello world2

#バイナリファイル書き込み
#rubyの文字列はバイナリも格納できるらしい
#で、Arrayのpack、stringのunpackで色々できる
#pack、unpackはPerlから持ってきているらしい。
#が正直よくわかんね。
def f3()
  f = File.open("./test3.dat","ab")
  begin
    buf = [0,1,2].pack('S*')
    f.write buf
  ensure
    f.close
  end
end

#バイナリファイル読み込み
def f4()
  f = File.open("./test3.dat", "rb")
  begin
    until f.eof? do
      l = f.gets
      arr = l.unpack('S*')
      arr.each {|b| printf("%d\n",b) }
    end
  ensure
  end
end

f3()
f4()
#->0
#  1
#  2