Ruby - File Open Mode

Introduction

You can use several different file modes, as covered in the following table.

File Mode
properties of the I/O Stream
r
Read-only. The file pointer is placed at the start of the file.
r+
Both reading and writing are allowed. The file pointer is placed at the start of the file.
w
Write-only. A new file is created (or an old one overwritten as if new).
w+
Both reading and writing are allowed, but File.new creates a new file from scratch
a
Write in append mode. The file pointer is placed at the end of the file.
a+

Both reading and writing are allowed in append mode. The file pointer is placed at
the end of the file.
b


Binary file mode. You can use it in conjunction with any of the other modes listed.
This mode is optional in Ruby 1.8 except on Windows but is required in Ruby 1.9 if
you are reading files that are not just text.

Related Topics