ファイルをオープンする

f = open('test.txt')		# ファイルをオープン
f.close			# ファイルを閉じる
# open('test.txt','w')		# 書き込みモードでファイルをオープン

open('test.txt') {|f|
	
}	# ファイルは自動で閉じられる
begin
	f = open('test_.txt')
	f.close
rescue => err
	if err.class==Errno::ENOENT
		puts "error: ファイルがない"
	else
		# それ以外のエラー
		puts "error: #{err.class}; #{err.message}"
	end
end

ファイルのオープンに失敗すると例外が発生する.


バイナリモードで読みこむ

fd = File.open('data.dat')
fd.binmode
a = fd.read() # サイズを指定しないと終わりまで全部読む
p a.unpack('H*') # 16進数にする
open('|dir') {|f|
	f.each {|l| p l}
}

'|'で始まるファイルはコマンドとして実行し,ファイルへの書き込みは標準入力への入力.
ファイルの読み込みは標準出力からの出力として扱える?