Rubyでファイルの読み込み
Rubyの読み込みはブロックの読み込みが一般的なようです。
ブロックは、{}で囲んだ方法です。
特徴は、open,closeが不要です。
■1行ずつ読み込み
File.open("sample.txt","r") do |f|
while line = f.gets
puts(line)
end
end
■1行ずつ読み(使えるのかな)
num = 1
File.open("sample.txt","r") do |f|
f.each_line{|line|
puts(num.to_s + ": " + line)
num = num + 1
}
end
■指定のバイト数を読み込む
File.open("sample.txt","r") do |f|
puts(f.read(10))
puts(f.read)
end
■各行を配列の要素として読み込む
File.open("sample.txt","r") do |f|
lines = f.readlines
puts(lines[0]) #1行目を出力
end
■ファイルにデータを書き込む
File.open("sample.txt","w") do |f|
f.puts("sunday") #改行付きで出力
f.print("monday") #改行なしで出力
end
■バイナリファイルの読み込み(ブロック未使用)
io = File.open("aa.jpg","rb")
buf = io.read(400)
m = buf.unpack("i*")
p m[0]
■文字配列をファイルに書き込む
a = ["C++","COBOL,"FORTRAN","Go"]
File.open("sample.txt","w") do |f|
a.each{|s|
f.puts(s)
}
end
■バイナリファイルの読み込みと書き込み
File.open("aa.jpg","rb") do |infile|
File.open("bb.jpg",wb") do |outfile|
while d = infile.read(1)
outfile.write(d)
end
end
end
■簡単な読み込み
a = File.read("aa.jpg") #ファイルの読み込み
File.write("bb.jpg",a) #ファイルの書き出し