LoginSignup
20
17

More than 5 years have passed since last update.

Ruby の IO.read でバイナリファイルを読み込むときの注意点

Last updated at Posted at 2013-04-17

IO.read の挙動

Ruby の IO.read は 引数 length が指定された場合バイナリ読み込みモードとして、そうでない場合テキスト読み込みモードとして動作します。

test.rb
file_size = File.size("./hoge.tif")
read = File.read("./hoge.tif")

p "file size: #{file_size}"
p "read size: #{read.size}"
実行結果
$ ruby1.9.3 test.rb
"file size: 53642"
"read size: 52181" # テキストエンコーディングの影響でサイズが変わってしまっている

したがってこのように、バイナリモードで読み込んでいるつもりでテキストモードとして誤って読み込んでしまうことがあります。

IO.binread

引数 length を指定しなくてもバイナリモードとして読み込んでもらいたい場合、 IO.binread があります。

test2.rb
file_size = File.size("./hoge.tif")
read = File.binread("./hoge.tif")

p "file size: #{file_size}"
p "read size: #{read.size}"

実行結果
$ ruby1.9.3 test2.rb
"file size: 53642"
"read size: 53642" # バイナリとして読み込んだのでサイズが一致している

参考

class IO

20
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
17