O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.17. Processing a Binary File

Problem

You want to read binary data from a file, or write it to one.

Solution

Since Ruby strings make no distinction between binary and text data, processing a binary file needn't be any different than processing a text file. Just make sure you add "b" to your file mode when you open a binary file on Windows.

This code writes 10 bytes of binary data to a file, then reads it back:

	open('binary', 'wb') do |f|
	  (0..100).step(10) { |b| f << b.chr }
	end
	
	s = open('binary', 'rb') { |f| f.read }
	# => "\000\n\024\036(2<FPZd"

If you want to process a binary file one byte at a time, you'll probably enjoy the way each_byte returns each byte of the file as a number, rather than as single-character strings:

	open('binary', 'rb') { |f| f.each_byte { |b| puts b } }
	# 0
	# 10
	# 20
	# …
	# 90
	# 100

Discussion

The methods introduced earlier to deal with text files work just as well for binary files, assuming that your binary files are supposed to be processed from beginning to end, the way text files typically are. If you want random access to the contents of a binary file, you can manipulate your file object's "cursor."

Think of the cursor as a pointer to the first unread byte in the open file. The current position of the cursor is accessed by the method IO#pos. When you open the file, it's set to zero, just before the first byte. You can then use IO#read to read a number of bytes starting from the current position of the cursor, incrementing the cursor as a side effect.

 f = open('binary') ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required