method
open
open(...)
public
Register or
log in
to add new notes.
RISCfuture -
January 14, 2009
Soleone -
February 12, 2009
6 thanks
File open permissions
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'
4 thanks
Binary files
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. :)

