method

open

v1_8_7_72 - Show latest stable - Class: IO
open(...)
public

With no associated block, open is a synonym for IO::new. If the optional code block is given, it will be passed io as an argument, and the IO object will automatically be closed when the block terminates. In this instance, IO::open returns the value of the block.

4Notes

File open permissions

RISCfuture · Jan 14, 20096 thanks

Usage: File.open path, flags, [permissions]

== Flags (bitmasks)

Access:

File::RDONLY:: Read-only File::WRONLY:: Write-only File::RDWR:: Read and write

If the file exists:

File::TRUNC:: Truncate File::APPEND:: Append File::EXCL:: Fail

If the file doesn't exist:

File::CREAT:: Create

== Flags (strings)

r:: File::RDONLY r+:: File::RDWR w:: File::WRONLY|File::TRUNC|File::CREAT a:: File::WRONLY|File::APPEND|File::CREAT

== Examples

File.open path, File::RDONLY File.open path, 'w' File.open path, File::WRONLY|File::TRUNC|File::CREAT File.open path, File::WRONLY|File::TRUNC|File::CREAT, '0666'

Binary files

Soleone · Feb 11, 20094 thanks

Another real important flag is b when dealing with binary files. For example to download an mp3 from the internet you need to pass the b flag or the data will be screwed up:

# Downloads a binary file from the internet
require 'open-uri'
url = "http://fubar/song.mp3"
open(url, 'rb') do |mp3|
File.open("local.mp3", 'wb') do |file|
  file.write(mp3.read)
end
end

Don't say you haven't been warned. :)

Errors Raised

sshaw · Apr 21, 2010

Non +IO+ errors (+IOError+) are contained in the +Errno+ module. They are the same as those given in open(2), see:

http://www.kernel.org/doc/man-pages/online/pages/man2/open.2.html#ERRORS

== Common Errors

  • Errno::ENOENT: No such file or directory
  • Errno::EACCES: Permission denied
  • Errno::EEXIST: File exists (i.e. IO::EXCL | IO::CREAT)

Mode Flags

sshaw · Apr 21, 2010

+RDONLY+, +TRUNC+, etc... are defined in the File::Constants module which is +include+'d by +IO+ and +File+.

IO.open fd, IO::RDONLY File.open path, File::RDONLY

Though as pointed out above, they are interchangeable.