Class: File
Overview
A File object is a representation of a file in the underlying platform.
Class File extends module FileTest, supporting such singleton methods as File.exist?
.
About the Examples
Many examples here use these variables:
:include: doc/examples/files.rdoc
Access Modes
Methods File.new and File.open each create a File object for a given file path.
String Access Modes
Methods File.new and File.open each may take string argument mode
, which:
-
Begins with a 1- or 2-character read/write mode.
-
May also contain a 1-character data mode.
-
May also contain a 1-character file-create mode.
Read/Write Mode
The read/write mode
determines:
-
Whether the file is to be initially truncated.
-
Whether reading is allowed, and if so:
-
The initial read position in the file.
-
Where in the file reading can occur.
-
-
Whether writing is allowed, and if so:
-
The initial write position in the file.
-
Where in the file writing can occur.
-
These tables summarize:
Read/Write Modes for Existing File
|------|-----------|----------|----------|----------|-----------|
| R/W | Initial | | Initial | | Initial |
| Mode | Truncate? | Read | Read Pos | Write | Write Pos |
|------|-----------|----------|----------|----------|-----------|
| 'r' | No | Anywhere | 0 | Error | - |
| 'w' | Yes | Error | - | Anywhere | 0 |
| 'a' | No | Error | - | End only | End |
| 'r+' | No | Anywhere | 0 | Anywhere | 0 |
| 'w+' | Yes | Anywhere | 0 | Anywhere | 0 |
| 'a+' | No | Anywhere | End | End only | End |
|------|-----------|----------|----------|----------|-----------|
Read/Write Modes for \File To Be Created
|------|----------|----------|----------|-----------|
| R/W | | Initial | | Initial |
| Mode | Read | Read Pos | Write | Write Pos |
|------|----------|----------|----------|-----------|
| 'w' | Error | - | Anywhere | 0 |
| 'a' | Error | - | End only | 0 |
| 'w+' | Anywhere | 0 | Anywhere | 0 |
| 'a+' | Anywhere | 0 | End only | End |
|------|----------|----------|----------|-----------|
Note that modes 'r'
and 'r+'
are not allowed for a non-existent file (exception raised).
In the tables:
-
Anywhere
means that methods IO#rewind, IO#pos=, and IO#seek may be used to change the file’s position, so that allowed reading or writing may occur anywhere in the file. -
End only
means that writing can occur only at end-of-file, and that methods IO#rewind, IO#pos=, and IO#seek do not affect writing. -
Error
means that an exception is raised if disallowed reading or writing is attempted.
Read/Write Modes for Existing File
-
'r'
:-
File is not initially truncated:
f = File.new('t.txt') # => #<File:t.txt> f.size == 0 # => false
-
File’s initial read position is 0:
f.pos # => 0
-
File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
f.readline # => "First line\n" f.readline # => "Second line\n" f.rewind f.readline # => "First line\n" f.pos = 1 f.readline # => "irst line\n" f.seek(1, :CUR) f.readline # => "econd line\n"
-
Writing is not allowed:
f.write('foo') # Raises IOError.
-
-
'w'
:-
File is initially truncated:
path = 't.tmp' File.write(path, text) f = File.new(path, 'w') f.size == 0 # => true
-
File’s initial write position is 0:
f.pos # => 0
-
File may be written anywhere (even past end-of-file); see IO#rewind, IO#pos=, IO#seek:
f.write('foo') f.flush File.read(path) # => "foo" f.pos # => 3 f.write('bar') f.flush File.read(path) # => "foobar" f.pos # => 6 f.rewind f.write('baz') f.flush File.read(path) # => "bazbar" f.pos # => 3 f.pos = 3 f.write('foo') f.flush File.read(path) # => "bazfoo" f.pos # => 6 f.seek(-3, :END) f.write('bam') f.flush File.read(path) # => "bazbam" f.pos # => 6 f.pos = 8 f.write('bah') # Zero padding as needed. f.flush File.read(path) # => "bazbam\u0000\u0000bah" f.pos # => 11
-
Reading is not allowed:
f.read # Raises IOError.
-
-
'a'
:-
File is not initially truncated:
path = 't.tmp' File.write(path, 'foo') f = File.new(path, 'a') f.size == 0 # => false
-
File’s initial position is 0 (but is ignored):
f.pos # => 0
-
File may be written only at end-of-file; IO#rewind, IO#pos=, IO#seek do not affect writing:
f.write('bar') f.flush File.read(path) # => "foobar" f.write('baz') f.flush File.read(path) # => "foobarbaz" f.rewind f.write('bat') f.flush File.read(path) # => "foobarbazbat"
-
Reading is not allowed:
f.read # Raises IOError.
-
-
'r+'
:-
File is not initially truncated:
path = 't.tmp' File.write(path, text) f = File.new(path, 'r+') f.size == 0 # => false
-
File’s initial read position is 0:
f.pos # => 0
-
File may be read or written anywhere (even past end-of-file); see IO#rewind, IO#pos=, IO#seek:
f.readline # => "First line\n" f.readline # => "Second line\n" f.rewind f.readline # => "First line\n" f.pos = 1 f.readline # => "irst line\n" f.seek(1, :CUR) f.readline # => "econd line\n" f.rewind f.write('WWW') f.flush File.read(path) # => "WWWst line\nSecond line\nFourth line\nFifth line\n" f.pos = 10 f.write('XXX') f.flush File.read(path) # => "WWWst lineXXXecond line\nFourth line\nFifth line\n" f.seek(-6, :END) # => 0 f.write('YYY') # => 3 f.flush # => #<File:t.tmp> File.read(path) # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n" f.seek(2, :END) f.write('ZZZ') # Zero padding as needed. f.flush File.read(path) # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n\u0000\u0000ZZZ"
-
-
'a+'
:-
File is not initially truncated:
path = 't.tmp' File.write(path, 'foo') f = File.new(path, 'a+') f.size == 0 # => false
-
File’s initial read position is 0:
f.pos # => 0
-
File may be written only at end-of-file; IO#rewind, IO#pos=, IO#seek do not affect writing:
f.write('bar') f.flush File.read(path) # => "foobar" f.write('baz') f.flush File.read(path) # => "foobarbaz" f.rewind f.write('bat') f.flush File.read(path) # => "foobarbazbat"
-
File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
f.rewind f.read # => "foobarbazbat" f.pos = 3 f.read # => "barbazbat" f.seek(-3, :END) f.read # => "bat"
-
Read/Write Modes for File To Be Created
Note that modes 'r'
and 'r+'
are not allowed for a non-existent file (exception raised).
-
'w'
:-
File’s initial write position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'w') f.pos # => 0
-
File may be written anywhere (even past end-of-file); see IO#rewind, IO#pos=, IO#seek:
f.write('foo') f.flush File.read(path) # => "foo" f.pos # => 3 f.write('bar') f.flush File.read(path) # => "foobar" f.pos # => 6 f.rewind f.write('baz') f.flush File.read(path) # => "bazbar" f.pos # => 3 f.pos = 3 f.write('foo') f.flush File.read(path) # => "bazfoo" f.pos # => 6 f.seek(-3, :END) f.write('bam') f.flush File.read(path) # => "bazbam" f.pos # => 6 f.pos = 8 f.write('bah') # Zero padding as needed. f.flush File.read(path) # => "bazbam\u0000\u0000bah" f.pos # => 11
-
Reading is not allowed:
f.read # Raises IOError.
-
-
'a'
:-
File’s initial write position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'a') f.pos # => 0
-
Writing occurs only at end-of-file:
f.write('foo') f.pos # => 3 f.write('bar') f.pos # => 6 f.flush File.read(path) # => "foobar" f.rewind f.write('baz') f.flush File.read(path) # => "foobarbaz"
-
Reading is not allowed:
f.read # Raises IOError.
-
-
'w+'
:-
File’s initial position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'w+') f.pos # => 0
-
File may be written anywhere (even past end-of-file); see IO#rewind, IO#pos=, IO#seek:
f.write('foo') f.flush File.read(path) # => "foo" f.pos # => 3 f.write('bar') f.flush File.read(path) # => "foobar" f.pos # => 6 f.rewind f.write('baz') f.flush File.read(path) # => "bazbar" f.pos # => 3 f.pos = 3 f.write('foo') f.flush File.read(path) # => "bazfoo" f.pos # => 6 f.seek(-3, :END) f.write('bam') f.flush File.read(path) # => "bazbam" f.pos # => 6 f.pos = 8 f.write('bah') # Zero padding as needed. f.flush File.read(path) # => "bazbam\u0000\u0000bah" f.pos # => 11
-
File may be read anywhere (even past end-of-file); see IO#rewind, IO#pos=, IO#seek:
f.rewind # => 0 f.read # => "bazbam\u0000\u0000bah" f.pos = 3 # => 3 f.read # => "bam\u0000\u0000bah" f.seek(-3, :END) # => 0 f.read # => "bah"
-
-
'a+'
:-
File’s initial write position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'a+') f.pos # => 0
-
Writing occurs only at end-of-file:
f.write('foo') f.pos # => 3 f.write('bar') f.pos # => 6 f.flush File.read(path) # => "foobar" f.rewind f.write('baz') f.flush File.read(path) # => "foobarbaz"
-
File may be read anywhere (even past end-of-file); see IO#rewind, IO#pos=, IO#seek:
f.rewind f.read # => "foobarbaz" f.pos = 3 f.read # => "barbaz" f.seek(-3, :END) f.read # => "baz" f.pos = 800 f.read # => ""
-
Data Mode
To specify whether data is to be treated as text or as binary data, either of the following may be suffixed to any of the string read/write modes above:
-
't'
: Text data; sets the default external encoding toEncoding::UTF_8
; on Windows, enables conversion between EOL and CRLF and enables interpreting0x1A
as an end-of-file marker. -
'b'
: Binary data; sets the default external encoding toEncoding::ASCII_8BIT
; on Windows, suppresses conversion between EOL and CRLF and disables interpreting0x1A
as an end-of-file marker.
If neither is given, the stream defaults to text data.
Examples:
File.new('t.txt', 'rt')
File.new('t.dat', 'rb')
When the data mode is specified, the read/write mode may not be omitted, and the data mode must precede the file-create mode, if given:
File.new('t.dat', 'b') # Raises an exception.
File.new('t.dat', 'rxb') # Raises an exception.
File-Create Mode
The following may be suffixed to any writable string mode above:
-
'x'
: Creates the file if it does not exist; raises an exception if the file exists.
Example:
File.new('t.tmp', 'wx')
When the file-create mode is specified, the read/write mode may not be omitted, and the file-create mode must follow the data mode:
File.new('t.dat', 'x') # Raises an exception.
File.new('t.dat', 'rxb') # Raises an exception.
Integer Access Modes
When mode is an integer it must be one or more of the following constants, which may be combined by the bitwise OR operator |
:
-
File::RDONLY
: Open for reading only. -
File::WRONLY
: Open for writing only. -
File::RDWR
: Open for reading and writing. -
File::APPEND
: Open for appending only.
Examples:
File.new('t.txt', File::RDONLY)
File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)
Note: Method IO#set_encoding does not allow the mode to be specified as an integer.
File-Create Mode Specified as an Integer
These constants may also be ORed into the integer mode:
-
File::CREAT
: Create file if it does not exist. -
File::EXCL
: Raise an exception ifFile::CREAT
is given and the file exists.
Data Mode Specified as an Integer
Data mode cannot be specified as an integer. When the stream access mode is given as an integer, the data mode is always text, never binary.
Note that although there is a constant File::BINARY
, setting its value in an integer stream mode has no effect; this is because, as documented in File::Constants, the File::BINARY
value disables line code conversion, but does not change the external encoding.
Encodings
Any of the string modes above may specify encodings - either external encoding only or both external and internal encodings - by appending one or both encoding names, separated by colons:
f = File.new('t.dat', 'rb')
f.external_encoding # => #<Encoding:ASCII-8BIT>
f.internal_encoding # => nil
f = File.new('t.dat', 'rb:UTF-16')
f.external_encoding # => #<Encoding:UTF-16 (dummy)>
f.internal_encoding # => nil
f = File.new('t.dat', 'rb:UTF-16:UTF-16')
f.external_encoding # => #<Encoding:UTF-16 (dummy)>
f.internal_encoding # => #<Encoding:UTF-16>
f.close
The numerous encoding names are available in array Encoding.name_list:
Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]
When the external encoding is set, strings read are tagged by that encoding when reading, and strings written are converted to that encoding when writing.
When both external and internal encodings are set, strings read are converted from external to internal encoding, and strings written are converted from internal to external encoding. For further details about transcoding input and output, see Encodings.
If the external encoding is 'BOM|UTF-8'
, 'BOM|UTF-16LE'
or 'BOM|UTF16-BE'
, Ruby checks for a Unicode BOM in the input document to help determine the encoding. For UTF-16 encodings the file open mode must be binary. If the BOM is found, it is stripped and the external encoding from the BOM is used.
Note that the BOM-style encoding option is case insensitive, so 'bom|utf-8'
is also valid.
File Permissions
A File object has permissions, an octal integer representing the permissions of an actual file in the underlying platform.
Note that file permissions are quite different from the mode of a file stream (File object).
In a File object, the permissions are available thus, where method mode
, despite its name, returns permissions:
f = File.new('t.txt')
f.lstat.mode.to_s(8) # => "100644"
On a Unix-based operating system, the three low-order octal digits represent the permissions for owner (6), group (4), and world (4). The triplet of bits in each octal digit represent, respectively, read, write, and execute permissions.
Permissions 0644
thus represent read-write access for owner and read-only access for group and world. See man pages open(2) and chmod(2).
For a directory, the meaning of the execute bit changes: when set, the directory can be searched.
Higher-order bits in permissions may indicate the type of file (plain, directory, pipe, socket, etc.) and various other special features.
On non-Posix operating systems, permissions may include only read-only or read-write, in which case, the remaining permission will resemble typical values. On Windows, for instance, the default permissions are 0644
; The only change that can be made is to make the file read-only, which is reported as 0444
.
For a method that actually creates a file in the underlying platform (as opposed to merely creating a File object), permissions may be specified:
File.new('t.tmp', File::CREAT, 0644)
File.new('t.tmp', File::CREAT, 0444)
Permissions may also be changed:
f = File.new('t.tmp', File::CREAT, 0444)
f.chmod(0644)
f.chmod(0444)
File Constants
Various constants for use in File and IO methods may be found in module File::Constants; an array of their names is returned by File::Constants.constants
.
What’s Here
First, what’s elsewhere. Class File:
-
Inherits from class IO, in particular, methods for creating, reading, and writing files
-
Includes module FileTest, which provides dozens of additional methods.
Here, class File provides methods that are useful for:
Creating
-
::new: Opens the file at the given path; returns the file.
-
::open: Same as ::new, but when given a block will yield the file to the block, and close the file upon exiting the block.
-
::link: Creates a new name for an existing file using a hard link.
-
::mkfifo: Returns the FIFO file created at the given path.
-
::symlink: Creates a symbolic link for the given file path.
Querying
Paths
-
::absolute_path: Returns the absolute file path for the given path.
-
::absolute_path?: Returns whether the given path is the absolute file path.
-
::basename: Returns the last component of the given file path.
-
::dirname: Returns all but the last component of the given file path.
-
::expand_path: Returns the absolute file path for the given path, expanding
~
for a home directory. -
::extname: Returns the file extension for the given file path.
-
::fnmatch? (aliased as ::fnmatch): Returns whether the given file path matches the given pattern.
-
::join: Joins path components into a single path string.
-
::path: Returns the string representation of the given path.
-
::readlink: Returns the path to the file at the given symbolic link.
-
::realdirpath: Returns the real path for the given file path, where the last component need not exist.
-
::realpath: Returns the real path for the given file path, where all components must exist.
-
::split: Returns an array of two strings: the directory name and basename of the file at the given path.
-
#path (aliased as #to_path): Returns the string representation of the given path.
Times
-
::atime: Returns a Time for the most recent access to the given file.
-
::birthtime: Returns a Time for the creation of the given file.
-
::ctime: Returns a Time for the metadata change of the given file.
-
::mtime: Returns a Time for the most recent data modification to the content of the given file.
-
#atime: Returns a Time for the most recent access to
self
. -
#birthtime: Returns a Time the creation for
self
. -
#ctime: Returns a Time for the metadata change of
self
. -
#mtime: Returns a Time for the most recent data modification to the content of
self
.
Types
-
::blockdev?: Returns whether the file at the given path is a block device.
-
::chardev?: Returns whether the file at the given path is a character device.
-
::directory?: Returns whether the file at the given path is a directory.
-
::executable?: Returns whether the file at the given path is executable by the effective user and group of the current process.
-
::executable_real?: Returns whether the file at the given path is executable by the real user and group of the current process.
-
::exist?: Returns whether the file at the given path exists.
-
::file?: Returns whether the file at the given path is a regular file.
-
::ftype: Returns a string giving the type of the file at the given path.
-
::grpowned?: Returns whether the effective group of the current process owns the file at the given path.
-
::identical?: Returns whether the files at two given paths are identical.
-
::lstat: Returns the File::Stat object for the last symbolic link in the given path.
-
::owned?: Returns whether the effective user of the current process owns the file at the given path.
-
::pipe?: Returns whether the file at the given path is a pipe.
-
::readable?: Returns whether the file at the given path is readable by the effective user and group of the current process.
-
::readable_real?: Returns whether the file at the given path is readable by the real user and group of the current process.
-
::setgid?: Returns whether the setgid bit is set for the file at the given path.
-
::setuid?: Returns whether the setuid bit is set for the file at the given path.
-
::socket?: Returns whether the file at the given path is a socket.
-
::stat: Returns the File::Stat object for the file at the given path.
-
::sticky?: Returns whether the file at the given path has its sticky bit set.
-
::symlink?: Returns whether the file at the given path is a symbolic link.
-
::umask: Returns the umask value for the current process.
-
::world_readable?: Returns whether the file at the given path is readable by others.
-
::world_writable?: Returns whether the file at the given path is writable by others.
-
::writable?: Returns whether the file at the given path is writable by the effective user and group of the current process.
-
::writable_real?: Returns whether the file at the given path is writable by the real user and group of the current process.
-
#lstat: Returns the File::Stat object for the last symbolic link in the path for
self
.
Contents
-
::empty? (aliased as ::zero?): Returns whether the file at the given path exists and is empty.
-
::size: Returns the size (bytes) of the file at the given path.
-
::size?: Returns
nil
if there is no file at the given path, or if that file is empty; otherwise returns the file size (bytes). -
#size: Returns the size (bytes) of
self
.
Settings
-
::chmod: Changes permissions of the file at the given path.
-
::chown: Change ownership of the file at the given path.
-
::lchmod: Changes permissions of the last symbolic link in the given path.
-
::lchown: Change ownership of the last symbolic in the given path.
-
::lutime: For each given file path, sets the access time and modification time of the last symbolic link in the path.
-
::rename: Moves the file at one given path to another given path.
-
::utime: Sets the access time and modification time of each file at the given paths.
-
#flock: Locks or unlocks
self
.
Other
-
::truncate: Truncates the file at the given file path to the given size.
-
::unlink (aliased as ::delete): Deletes the file for each given file path.
-
#truncate: Truncates
self
to the given size.
Defined Under Namespace
Modules: Constants Classes: Stat
Constant Summary collapse
- Separator =
separates directory parts in path
separator
- SEPARATOR =
separates directory parts in path
separator
- ALT_SEPARATOR =
platform specific alternative separator
Qnil
- PATH_SEPARATOR =
path list separator
rb_fstring_cstr(PATH_SEP)
Constants inherited from IO
IO::PRIORITY, IO::READABLE, IO::SEEK_CUR, IO::SEEK_DATA, IO::SEEK_END, IO::SEEK_HOLE, IO::SEEK_SET, IO::WRITABLE
Constants included from Constants
Constants::APPEND, Constants::BINARY, Constants::CREAT, Constants::DIRECT, Constants::DSYNC, Constants::EXCL, Constants::LOCK_EX, Constants::LOCK_NB, Constants::LOCK_SH, Constants::LOCK_UN, Constants::NOATIME, Constants::NOCTTY, Constants::NOFOLLOW, Constants::NONBLOCK, Constants::NULL, Constants::RDONLY, Constants::RDWR, Constants::RSYNC, Constants::SHARE_DELETE, Constants::SYNC, Constants::TMPFILE, Constants::TRUNC, Constants::WRONLY
Class Method Summary collapse
-
.absolute_path(file_name[, dir_string]) ⇒ Object
Converts a pathname to an absolute pathname.
-
.absolute_path?(file_name) ⇒ Boolean
Returns
true
iffile_name
is an absolute path, andfalse
otherwise. -
.atime(file_name) ⇒ Time
Returns the last access time for the named file as a Time object.
-
.basename(file_name[, suffix]) ⇒ Object
Returns the last component of the filename given in file_name (after first stripping trailing separators), which can be formed using both File::SEPARATOR and File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is not
nil
. -
.birthtime(file_name) ⇒ Time
Returns the birth time for the named file.
-
.blockdev?(filepath) ⇒ Boolean
Returns
true
iffilepath
points to a block device,false
otherwise:. -
.chardev?(filepath) ⇒ Boolean
Returns
true
iffilepath
points to a character device,false
otherwise. -
.chmod(mode_int, file_name, ...) ⇒ Integer
Changes permission bits on the named file(s) to the bit pattern represented by mode_int.
-
.chown(owner_int, group_int, file_name, ...) ⇒ Integer
Changes the owner and group of the named file(s) to the given numeric owner and group id’s.
-
.ctime(file_name) ⇒ Time
Returns the change time for the named file (the time at which directory information about the file was changed, not the file itself).
-
.delete(*args) ⇒ Object
Deletes the named files, returning the number of names passed as arguments.
-
.directory?(path) ⇒ Boolean
With string
object
given, returnstrue
ifpath
is a string path leading to a directory, or to a symbolic link to a directory;false
otherwise:. -
.dirname(file_name, level = 1) ⇒ Object
Returns all components of the filename given in file_name except the last one (after first stripping trailing separators).
-
.zero?(file_name) ⇒ Boolean
Returns
true
if the named file exists and has a zero size. -
.executable?(file_name) ⇒ Boolean
Returns
true
if the named file is executable by the effective user and group id of this process. -
.executable_real?(file_name) ⇒ Boolean
Returns
true
if the named file is executable by the real user and group id of this process. -
.exist?(file_name) ⇒ Boolean
Return
true
if the named file exists. -
.expand_path(file_name[, dir_string]) ⇒ Object
Converts a pathname to an absolute pathname.
-
.extname(path) ⇒ String
Returns the extension (the portion of file name in
path
starting from the last period). -
.file?(file) ⇒ Boolean
Returns
true
if the namedfile
exists and is a regular file. -
.fnmatch(*args) ⇒ Object
:nodoc:.
-
.fnmatch?(*args) ⇒ Boolean
:nodoc:.
-
.ftype(file_name) ⇒ String
Identifies the type of the named file; the return string is one of “
file
”, “directory
”, “characterSpecial
”, “blockSpecial
”, “fifo
”, “link
”, “socket
”, or “unknown
”. -
.grpowned?(file_name) ⇒ Boolean
Returns
true
if the named file exists and the effective group id of the calling process is the owner of the file. -
.identical?(file_1, file_2) ⇒ Boolean
Returns
true
if the named files are identical. -
.join(string, ...) ⇒ String
Returns a new string formed by joining the strings using
"/"
. -
.lchmod(mode_int, file_name, ...) ⇒ Integer
Equivalent to File::chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link).
-
.lchown(owner_int, group_int, file_name, ..) ⇒ Integer
Equivalent to File::chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link).
-
.link(old_name, new_name) ⇒ 0
Creates a new name for an existing file using a hard link.
-
.lstat(filepath) ⇒ Object
Like File::stat, but does not follow the last symbolic link; instead, returns a File::Stat object for the link itself.
-
.lutime(atime, mtime, file_name, ...) ⇒ Integer
Sets the access and modification times of each named file to the first two arguments.
-
.mkfifo(file_name, mode = 0666) ⇒ 0
Creates a FIFO special file with name file_name.
-
.mtime(file_name) ⇒ Time
Returns the modification time for the named file as a Time object.
-
.open(*args) ⇒ Object
call-seq: IO.open(fd, mode = ‘r’, **opts) -> io IO.open(fd, mode = ‘r’, **opts) {|io| … } -> object.
-
.owned?(file_name) ⇒ Boolean
Returns
true
if the named file exists and the effective used id of the calling process is the owner of the file. -
.path(path) ⇒ String
Returns the string representation of the path.
-
.pipe?(filepath) ⇒ Boolean
Returns
true
iffilepath
points to a pipe,false
otherwise:. -
.readable?(file_name) ⇒ Boolean
Returns
true
if the named file is readable by the effective user and group id of this process. -
.readable_real?(file_name) ⇒ Boolean
Returns
true
if the named file is readable by the real user and group id of this process. -
.readlink(link_name) ⇒ Object
Returns the name of the file referenced by the given link.
-
.realdirpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual filesystem.
-
.realpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual filesystem not containing symlinks or useless dots.
-
.rename(old_name, new_name) ⇒ 0
Renames the given file to the new name.
-
.setgid?(file_name) ⇒ Boolean
Returns
true
if the named file has the setgid bit set. -
.setuid?(file_name) ⇒ Boolean
Returns
true
if the named file has the setuid bit set. -
.size(file_name) ⇒ Integer
Returns the size of
file_name
. -
.size?(file_name) ⇒ Integer?
Returns
nil
iffile_name
doesn’t exist or has zero size, the size of the file otherwise. -
.socket?(filepath) ⇒ Boolean
Returns
true
iffilepath
points to a socket,false
otherwise:. -
.split(file_name) ⇒ Array
Splits the given string into a directory and a file component and returns them in a two-element array.
-
.stat(filepath) ⇒ Object
Returns a File::Stat object for the file at
filepath
(see File::Stat):. -
.sticky?(file_name) ⇒ Boolean
Returns
true
if the named file has the sticky bit set. -
.symlink(old_name, new_name) ⇒ 0
Creates a symbolic link called new_name for the existing file old_name.
-
.symlink?(filepath) ⇒ Boolean
Returns
true
iffilepath
points to a symbolic link,false
otherwise:. -
.truncate(file_name, integer) ⇒ 0
Truncates the file file_name to be at most integer bytes long.
-
.umask(*args) ⇒ Object
Returns the current umask value for this process.
-
.unlink(*args) ⇒ Object
Deletes the named files, returning the number of names passed as arguments.
-
.utime(atime, mtime, file_name, ...) ⇒ Integer
Sets the access and modification times of each named file to the first two arguments.
-
.world_readable?(file_name) ⇒ Integer?
If file_name is readable by others, returns an integer representing the file permission bits of file_name.
-
.world_writable?(file_name) ⇒ Integer?
If file_name is writable by others, returns an integer representing the file permission bits of file_name.
-
.writable?(file_name) ⇒ Boolean
Returns
true
if the named file is writable by the effective user and group id of this process. -
.writable_real?(file_name) ⇒ Boolean
Returns
true
if the named file is writable by the real user and group id of this process. -
.zero?(file_name) ⇒ Boolean
Returns
true
if the named file exists and has a zero size.
Instance Method Summary collapse
-
#atime ⇒ Time
Returns the last access time (a Time object) for file, or epoch if file has not been accessed.
-
#birthtime ⇒ Time
Returns the birth time for file.
-
#chmod(mode_int) ⇒ 0
Changes permission bits on file to the bit pattern represented by mode_int.
-
#chown(owner_int, group_int) ⇒ 0
Changes the owner and group of file to the given numeric owner and group id’s.
-
#ctime ⇒ Time
Returns the change time for file (that is, the time directory information about the file was changed, not the file itself).
-
#flock(operation) ⇒ Object
:markup: markdown.
-
#new(path, mode = 'r', perm = 0666, **opts) ⇒ File
constructor
Opens the file at the given
path
according to the givenmode
; creates and returns a new File object for that file. -
#lstat ⇒ Object
Like File#stat, but does not follow the last symbolic link; instead, returns a File::Stat object for the link itself:.
-
#mtime ⇒ Time
Returns the modification time for file.
-
#size ⇒ Integer
Returns the size of file in bytes.
-
#truncate(integer) ⇒ 0
Truncates file to at most integer bytes.
Methods inherited from IO
#<<, #advise, #autoclose=, #autoclose?, #binmode, #binmode?, binread, binwrite, #close, #close_on_exec=, #close_on_exec?, #close_read, #close_write, #closed?, copy_stream, #each, #each_byte, #each_char, #each_codepoint, #each_line, #eof, #eof?, #external_encoding, #fcntl, #fdatasync, #fileno, #flush, for_fd, foreach, #fsync, #getbyte, #getc, #gets, #initialize_copy, #inspect, #internal_encoding, #ioctl, #isatty, #lineno, #lineno=, new, #path, #pid, pipe, popen, #pos, #pos=, #pread, #print, #printf, #putc, #puts, #pwrite, read, #read, #readbyte, #readchar, #readlines, readlines, #readpartial, #reopen, #rewind, #seek, select, #set_encoding, #set_encoding_by_bom, #stat, #sync, #sync=, sysopen, #sysread, #sysseek, #syswrite, #tell, #timeout, #timeout=, #to_io, #to_path, try_convert, #tty?, #ungetbyte, #ungetc, #wait, #wait_priority, #wait_readable, #wait_writable, #write, write
Methods included from Enumerable
#all?, #any?, #chain, #chunk, #chunk_while, #collect, #collect_concat, #compact, #count, #cycle, #detect, #drop, #drop_while, #each_cons, #each_entry, #each_slice, #each_with_index, #each_with_object, #entries, #filter, #filter_map, #find, #find_all, #find_index, #first, #flat_map, #grep, #grep_v, #group_by, #include?, #inject, #lazy, #map, #max, #max_by, #member?, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #partition, #reduce, #reject, #reverse_each, #select, #slice_after, #slice_before, #slice_when, #sort, #sort_by, #sum, #take, #take_while, #tally, #to_a, #to_h, #uniq, #zip
Constructor Details
#new(path, mode = 'r', perm = 0666, **opts) ⇒ File
Opens the file at the given path
according to the given mode
; creates and returns a new File object for that file.
The new File object is buffered mode (or non-sync mode), unless filename
is a tty. See IO#flush, IO#fsync, IO#fdatasync, and IO#sync=.
Argument path
must be a valid file path:
f = File.new('/etc/fstab')
f.close
f = File.new('t.txt')
f.close
Optional argument mode
(defaults to ‘r’) must specify a valid mode; see Access Modes:
f = File.new('t.tmp', 'w')
f.close
f = File.new('t.tmp', File::RDONLY)
f.close
Optional argument perm
(defaults to 0666) must specify valid permissions see File Permissions:
f = File.new('t.tmp', File::CREAT, 0644)
f.close
f = File.new('t.tmp', File::CREAT, 0444)
f.close
Optional keyword arguments opts
specify:
9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 |
# File 'io.c', line 9615 static VALUE rb_file_initialize(int argc, VALUE *argv, VALUE io) { if (RFILE(io)->fptr) { rb_raise(rb_eRuntimeError, "reinitializing File"); } if (0 < argc && argc < 3) { VALUE fd = rb_check_to_int(argv[0]); if (!NIL_P(fd)) { argv[0] = fd; return rb_io_initialize(argc, argv, io); } } rb_open_file(argc, argv, io); return io; } |
Class Method Details
.absolute_path(file_name[, dir_string]) ⇒ Object
Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. If the given pathname starts with a “~
” it is NOT expanded, it is treated as a normal directory name.
File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
4193 4194 4195 4196 4197 |
# File 'file.c', line 4193 static VALUE s_absolute_path(int c, const VALUE * v, VALUE _) { return rb_file_s_absolute_path(c, v); } |
.absolute_path?(file_name) ⇒ Boolean
Returns true
if file_name
is an absolute path, and false
otherwise.
File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
4209 4210 4211 4212 4213 4214 4215 4216 |
# File 'file.c', line 4209 static VALUE s_absolute_path_p(VALUE klass, VALUE fname) { VALUE path = rb_get_path(fname); if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse; return Qtrue; } |
.atime(file_name) ⇒ Time
Returns the last access time for the named file as a Time object.
file_name can be an IO object.
File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 |
# File 'file.c', line 2316 static VALUE rb_file_s_atime(VALUE klass, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return stat_atime(&st); } |
.basename(file_name[, suffix]) ⇒ Object
Returns the last component of the filename given in file_name (after first stripping trailing separators), which can be formed using both File::SEPARATOR and File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is not nil
. If suffix is given and present at the end of file_name, it is removed. If suffix is “.*”, any extension will be removed.
File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 |
# File 'file.c', line 4704 static VALUE rb_file_s_basename(int argc, VALUE *argv, VALUE _) { VALUE fname, fext, basename; const char *name, *p; long f, n; rb_encoding *enc; fext = Qnil; if (rb_check_arity(argc, 1, 2) == 2) { fext = argv[1]; StringValue(fext); enc = check_path_encoding(fext); } fname = argv[0]; FilePathStringValue(fname); if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) { enc = rb_enc_get(fname); fext = Qnil; } if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname))) return rb_str_new_shared(fname); p = ruby_enc_find_basename(name, &f, &n, enc); if (n >= 0) { if (NIL_P(fext)) { f = n; } else { const char *fp; fp = StringValueCStr(fext); if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) { f = n; } RB_GC_GUARD(fext); } if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname); } basename = rb_str_new(p, f); rb_enc_copy(basename, fname); return basename; } |
.birthtime(file_name) ⇒ Time
Returns the birth time for the named file.
file_name can be an IO object.
File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
If the platform doesn’t have birthtime, raises NotImplementedError.
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 |
# File 'file.c', line 2471 RUBY_FUNC_EXPORTED VALUE rb_file_s_birthtime(VALUE klass, VALUE fname) { statx_data st; if (rb_statx(fname, &st, STATX_BTIME) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return statx_birthtime(&st, fname); } |
.blockdev?(filepath) ⇒ Boolean
Returns true
if filepath
points to a block device, false
otherwise:
File.blockdev?('/dev/sda1') # => true
File.blockdev?(File.new('t.tmp')) # => false
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 |
# File 'file.c', line 1748 static VALUE rb_file_blockdev_p(VALUE obj, VALUE fname) { #ifndef S_ISBLK # ifdef S_IFBLK # define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) # else # define S_ISBLK(m) (0) /* anytime false */ # endif #endif #ifdef S_ISBLK struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISBLK(st.st_mode)) return Qtrue; #endif return Qfalse; } |
.chardev?(filepath) ⇒ Boolean
Returns true
if filepath
points to a character device, false
otherwise.
File.chardev?($stdin) # => true
File.chardev?('t.txt') # => false
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 |
# File 'file.c', line 1779 static VALUE rb_file_chardev_p(VALUE obj, VALUE fname) { #ifndef S_ISCHR # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) #endif struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISCHR(st.st_mode)) return Qtrue; return Qfalse; } |
.chmod(mode_int, file_name, ...) ⇒ Integer
Changes permission bits on the named file(s) to the bit pattern represented by mode_int. Actual effects are operating system dependent (see the beginning of this section). On Unix systems, see chmod(2)
for details. Returns the number of files processed.
File.chmod(0644, "testfile", "out") #=> 2
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 |
# File 'file.c', line 2574 static VALUE rb_file_s_chmod(int argc, VALUE *argv, VALUE _) { mode_t mode; apply2args(1); mode = NUM2MODET(*argv++); return apply2files(chmod_internal, argc, argv, &mode); } |
.chown(owner_int, group_int, file_name, ...) ⇒ Integer
Changes the owner and group of the named file(s) to the given numeric owner and group id’s. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file’s group to any group to which the owner belongs. A nil
or -1 owner or group id is ignored. Returns the number of files processed.
File.chown(nil, 100, "testfile")
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 |
# File 'file.c', line 2705 static VALUE rb_file_s_chown(int argc, VALUE *argv, VALUE _) { struct chown_args arg; apply2args(2); arg.owner = to_uid(*argv++); arg.group = to_gid(*argv++); return apply2files(chown_internal, argc, argv, &arg); } |
.ctime(file_name) ⇒ Time
Returns the change time for the named file (the time at which directory information about the file was changed, not the file itself).
file_name can be an IO object.
Note that on Windows (NTFS), returns creation time (birth time).
File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 |
# File 'file.c', line 2417 static VALUE rb_file_s_ctime(VALUE klass, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return stat_ctime(&st); } |
.delete(file_name, ...) ⇒ Integer .unlink(file_name, ...) ⇒ Integer
Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. Since the underlying implementation relies on the unlink(2)
system call, the type of exception raised depends on its error type (see linux.die.net/man/2/unlink) and has the form of e.g. Errno::ENOENT.
See also Dir::rmdir.
3201 3202 3203 3204 3205 |
# File 'file.c', line 3201 static VALUE rb_file_s_unlink(int argc, VALUE *argv, VALUE klass) { return apply2files(unlink_internal, argc, argv, 0); } |
.directory?(path) ⇒ Boolean
With string object
given, returns true
if path
is a string path leading to a directory, or to a symbolic link to a directory; false
otherwise:
File.directory?('.') # => true
File.directory?('foo') # => false
File.symlink('.', 'dirlink') # => 0
File.directory?('dirlink') # => true
File.symlink('t,txt', 'filelink') # => 0
File.directory?('filelink') # => false
Argument path
can be an IO object.
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 |
# File 'file.c', line 1614 VALUE rb_file_directory_p(VALUE obj, VALUE fname) { #ifndef S_ISDIR # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #endif struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISDIR(st.st_mode)) return Qtrue; return Qfalse; } |
.dirname(file_name, level = 1) ⇒ Object
Returns all components of the filename given in file_name except the last one (after first stripping trailing separators). The filename can be formed using both File::SEPARATOR and File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is not nil
.
File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
If level
is given, removes the last level
components, not only one.
File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4769 4770 4771 4772 4773 4774 4775 4776 4777 |
# File 'file.c', line 4769 static VALUE rb_file_s_dirname(int argc, VALUE *argv, VALUE klass) { int n = 1; if ((argc = rb_check_arity(argc, 1, 2)) > 1) { n = NUM2INT(argv[1]); } return rb_file_dirname_n(argv[0], n); } |
.zero?(file_name) ⇒ Boolean
Returns true
if the named file exists and has a zero size.
file_name can be an IO object.
2027 2028 2029 2030 2031 2032 2033 2034 |
# File 'file.c', line 2027 static VALUE rb_file_zero_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return RBOOL(st.st_size == 0); } |
.executable?(file_name) ⇒ Boolean
Returns true
if the named file is executable by the effective user and group id of this process. See eaccess(3).
Windows does not support execute permissions separately from read permissions. On Windows, a file is only considered executable if it ends in .bat, .cmd, .com, or .exe.
Note that some OS-level security features may cause this to return true even though the file is not executable by the effective user/group.
1965 1966 1967 1968 1969 |
# File 'file.c', line 1965 static VALUE rb_file_executable_p(VALUE obj, VALUE fname) { return RBOOL(rb_eaccess(fname, X_OK) >= 0); } |
.executable_real?(file_name) ⇒ Boolean
Returns true
if the named file is executable by the real user and group id of this process. See access(3).
Windows does not support execute permissions separately from read permissions. On Windows, a file is only considered executable if it ends in .bat, .cmd, .com, or .exe.
Note that some OS-level security features may cause this to return true even though the file is not executable by the real user/group.
1986 1987 1988 1989 1990 |
# File 'file.c', line 1986 static VALUE rb_file_executable_real_p(VALUE obj, VALUE fname) { return RBOOL(rb_access(fname, X_OK) >= 0); } |
.exist?(file_name) ⇒ Boolean
Return true
if the named file exists.
file_name can be an IO object.
“file exists” means that stat() or fstat() system call is successful.
1805 1806 1807 1808 1809 1810 1811 1812 |
# File 'file.c', line 1805 static VALUE rb_file_exist_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return Qtrue; } |
.expand_path(file_name[, dir_string]) ⇒ Object
Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string
is given, in which case it will be used as the starting point. The given pathname may start with a “~
”, which expands to the process owner’s home directory (the environment variable HOME
must be set correctly). “~
user” expands to the named user’s home directory.
File.("~oracle/bin") #=> "/home/oracle/bin"
A simple example of using dir_string
is as follows.
File.("ruby", "/usr/bin") #=> "/usr/bin/ruby"
A more complex example which also resolves parent directory is as follows. Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
File.("../../lib/mygem.rb", __FILE__)
#=> ".../path/to/project/lib/mygem.rb"
So first it resolves the parent of __FILE__, that is bin/, then go to the parent, the root of the project and appends lib/mygem.rb
.
4160 4161 4162 4163 4164 |
# File 'file.c', line 4160 static VALUE (int c, const VALUE * v, VALUE _) { return (c, v); } |
.extname(path) ⇒ String
Returns the extension (the portion of file name in path
starting from the last period).
If path
is a dotfile, or starts with a period, then the starting dot is not dealt with the start of the extension.
An empty string will also be returned when the period is the last character in path
.
On Windows, trailing dots are truncated.
File.extname("test.rb") #=> ".rb"
File.extname("a/b/d/test.rb") #=> ".rb"
File.extname(".a/b/d/test.rb") #=> ".rb"
File.extname("foo.") #=> "" on Windows
File.extname("foo.") #=> "." on non-Windows
File.extname("test") #=> ""
File.extname(".profile") #=> ""
File.extname(".profile.sh") #=> ".sh"
4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 |
# File 'file.c', line 4950 static VALUE rb_file_s_extname(VALUE klass, VALUE fname) { const char *name, *e; long len; VALUE extname; FilePathStringValue(fname); name = StringValueCStr(fname); len = RSTRING_LEN(fname); e = ruby_enc_find_extname(name, &len, rb_enc_get(fname)); if (len < 1) return rb_str_new(0, 0); extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */ return extname; } |
.file?(file) ⇒ Boolean
Returns true
if the named file
exists and is a regular file.
file
can be an IO object.
If the file
argument is a symbolic link, it will resolve the symbolic link and use the file referenced by the link.
2008 2009 2010 2011 2012 2013 2014 2015 |
# File 'file.c', line 2008 static VALUE rb_file_file_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return RBOOL(S_ISREG(st.st_mode)); } |
.fnmatch(*args) ⇒ Object
:nodoc:
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 |
# File 'dir.c', line 3456 static VALUE file_s_fnmatch(int argc, VALUE *argv, VALUE obj) { VALUE pattern, path; VALUE rflags; int flags; if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3) flags = NUM2INT(rflags); else flags = 0; StringValueCStr(pattern); FilePathStringValue(path); if (flags & FNM_EXTGLOB) { struct brace_args args; args.value = path; args.flags = flags; if ((RSTRING_PTR(pattern), flags, fnmatch_brace, (VALUE)&args, rb_enc_get(pattern), pattern) > 0) return Qtrue; } else { rb_encoding *enc = rb_enc_compatible(pattern, path); if (!enc) return Qfalse; if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0) return Qtrue; } RB_GC_GUARD(pattern); return Qfalse; } |
.fnmatch?(*args) ⇒ Boolean
:nodoc:
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 |
# File 'dir.c', line 3456 static VALUE file_s_fnmatch(int argc, VALUE *argv, VALUE obj) { VALUE pattern, path; VALUE rflags; int flags; if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3) flags = NUM2INT(rflags); else flags = 0; StringValueCStr(pattern); FilePathStringValue(path); if (flags & FNM_EXTGLOB) { struct brace_args args; args.value = path; args.flags = flags; if ((RSTRING_PTR(pattern), flags, fnmatch_brace, (VALUE)&args, rb_enc_get(pattern), pattern) > 0) return Qtrue; } else { rb_encoding *enc = rb_enc_compatible(pattern, path); if (!enc) return Qfalse; if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0) return Qtrue; } RB_GC_GUARD(pattern); return Qfalse; } |
.ftype(file_name) ⇒ String
Identifies the type of the named file; the return string is one of “file
”, “directory
”, “characterSpecial
”, “blockSpecial
”, “fifo
”, “link
”, “socket
”, or “unknown
”.
File.ftype("testfile") #=> "file"
File.ftype("/dev/tty") #=> "characterSpecial"
File.ftype("/tmp/.X11-unix/X0") #=> "socket"
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 |
# File 'file.c', line 2290 static VALUE rb_file_s_ftype(VALUE klass, VALUE fname) { struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) { rb_sys_fail_path(fname); } return rb_file_ftype(&st); } |
.grpowned?(file_name) ⇒ Boolean
Returns true
if the named file exists and the effective group id of the calling process is the owner of the file. Returns false
on Windows.
file_name can be an IO object.
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 |
# File 'file.c', line 2096 static VALUE rb_file_grpowned_p(VALUE obj, VALUE fname) { #ifndef _WIN32 struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (rb_group_member(st.st_gid)) return Qtrue; #endif return Qfalse; } |
.identical?(file_1, file_2) ⇒ Boolean
Returns true
if the named files are identical.
file_1 and file_2 can be an IO object.
open("a", "w") {}
p File.identical?("a", "a") #=> true
p File.identical?("a", "./a") #=> true
File.link("a", "b")
p File.identical?("a", "b") #=> true
File.symlink("a", "c")
p File.identical?("a", "c") #=> true
open("d", "w") {}
p File.identical?("a", "d") #=> false
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 |
# File 'file.c', line 2195 static VALUE rb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2) { #ifndef _WIN32 struct stat st1, st2; if (rb_stat(fname1, &st1) < 0) return Qfalse; if (rb_stat(fname2, &st2) < 0) return Qfalse; if (st1.st_dev != st2.st_dev) return Qfalse; if (st1.st_ino != st2.st_ino) return Qfalse; return Qtrue; #else extern VALUE rb_w32_file_identical_p(VALUE, VALUE); return rb_w32_file_identical_p(fname1, fname2); #endif } |
.join(string, ...) ⇒ String
Returns a new string formed by joining the strings using "/"
.
File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5086 5087 5088 5089 5090 |
# File 'file.c', line 5086 static VALUE rb_file_s_join(VALUE klass, VALUE args) { return rb_file_join(args); } |
.lchmod(mode_int, file_name, ...) ⇒ Integer
Equivalent to File::chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). Often not available.
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 |
# File 'file.c', line 2646 static VALUE rb_file_s_lchmod(int argc, VALUE *argv, VALUE _) { mode_t mode; apply2args(1); mode = NUM2MODET(*argv++); return apply2files(lchmod_internal, argc, argv, &mode); } |
.lchown(owner_int, group_int, file_name, ..) ⇒ Integer
Equivalent to File::chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). Often not available. Returns number of files in the argument list.
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 |
# File 'file.c', line 2777 static VALUE rb_file_s_lchown(int argc, VALUE *argv, VALUE _) { struct chown_args arg; apply2args(2); arg.owner = to_uid(*argv++); arg.group = to_gid(*argv++); return apply2files(lchown_internal, argc, argv, &arg); } |
.link(old_name, new_name) ⇒ 0
Creates a new name for an existing file using a hard link. Will not overwrite new_name if it already exists (raising a subclass of SystemCallError). Not available on all platforms.
File.link("testfile", ".testfile") #=> 0
IO.readlines(".testfile")[0] #=> "This is line one\n"
3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 |
# File 'file.c', line 3055 static VALUE rb_file_s_link(VALUE klass, VALUE from, VALUE to) { FilePathValue(from); FilePathValue(to); from = rb_str_encode_ospath(from); to = rb_str_encode_ospath(to); if (link(StringValueCStr(from), StringValueCStr(to)) < 0) { sys_fail2(from, to); } return INT2FIX(0); } |
.lstat(filepath) ⇒ Object
Like File::stat, but does not follow the last symbolic link; instead, returns a File::Stat object for the link itself.
File.symlink('t.txt', 'symlink')
File.stat('symlink').size # => 47
File.lstat('symlink').size # => 5
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 |
# File 'file.c', line 1403 static VALUE rb_file_s_lstat(VALUE klass, VALUE fname) { #ifdef HAVE_LSTAT struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) { rb_sys_fail_path(fname); } return rb_stat_new(&st); #else return rb_file_s_stat(klass, fname); #endif } |
.lutime(atime, mtime, file_name, ...) ⇒ Integer
Sets the access and modification times of each named file to the first two arguments. If a file is a symlink, this method acts upon the link itself as opposed to its referent; for the inverse behavior, see File.utime. Returns the number of file names in the argument list.
3001 3002 3003 3004 3005 |
# File 'file.c', line 3001 static VALUE rb_file_s_lutime(int argc, VALUE *argv, VALUE _) { return utime_internal_i(argc, argv, TRUE); } |
.mkfifo(file_name, mode = 0666) ⇒ 0
Creates a FIFO special file with name file_name. mode specifies the FIFO’s permissions. It is modified by the process’s umask in the usual way: the permissions of the created file are (mode & ~umask).
6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 |
# File 'file.c', line 6214 static VALUE rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _) { VALUE path; struct mkfifo_arg ma; ma.mode = 0666; rb_check_arity(argc, 1, 2); if (argc > 1) { ma.mode = NUM2MODET(argv[1]); } path = argv[0]; FilePathValue(path); path = rb_str_encode_ospath(path); ma.path = RSTRING_PTR(path); if (rb_thread_call_without_gvl(nogvl_mkfifo, &ma, RUBY_UBF_IO, 0)) { rb_sys_fail_path(path); } return INT2FIX(0); } |
.mtime(file_name) ⇒ Time
Returns the modification time for the named file as a Time object.
file_name can be an IO object.
File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 |
# File 'file.c', line 2365 static VALUE rb_file_s_mtime(VALUE klass, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return stat_mtime(&st); } |
.open(*args) ⇒ Object
call-seq:
IO.open(fd, mode = 'r', **opts) -> io
IO.open(fd, mode = 'r', **opts) {|io| ... } -> object
Creates a new IO object, via IO.new with the given arguments.
With no block given, returns the IO object.
With a block given, calls the block with the IO object and returns the block’s value.
8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 |
# File 'io.c', line 8147 static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass) { VALUE io = rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS); if (rb_block_given_p()) { return rb_ensure(rb_yield, io, io_close, io); } return io; } |
.owned?(file_name) ⇒ Boolean
Returns true
if the named file exists and the effective used id of the calling process is the owner of the file.
file_name can be an IO object.
2067 2068 2069 2070 2071 2072 2073 2074 |
# File 'file.c', line 2067 static VALUE rb_file_owned_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return RBOOL(st.st_uid == geteuid()); } |
.path(path) ⇒ String
Returns the string representation of the path
File.path(File::NULL) #=> "/dev/null"
File.path(Pathname.new("/tmp")) #=> "/tmp"
4978 4979 4980 4981 4982 |
# File 'file.c', line 4978 static VALUE rb_file_s_path(VALUE klass, VALUE fname) { return rb_get_path(fname); } |
.pipe?(filepath) ⇒ Boolean
Returns true
if filepath
points to a pipe, false
otherwise:
File.mkfifo('tmp/fifo')
File.pipe?('tmp/fifo') # => true
File.pipe?('t.txt') # => false
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 |
# File 'file.c', line 1640 static VALUE rb_file_pipe_p(VALUE obj, VALUE fname) { #ifdef S_IFIFO # ifndef S_ISFIFO # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) # endif struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISFIFO(st.st_mode)) return Qtrue; #endif return Qfalse; } |
.readable?(file_name) ⇒ Boolean
Returns true
if the named file is readable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not readable by the effective user/group.
1825 1826 1827 1828 1829 |
# File 'file.c', line 1825 static VALUE rb_file_readable_p(VALUE obj, VALUE fname) { return RBOOL(rb_eaccess(fname, R_OK) >= 0); } |
.readable_real?(file_name) ⇒ Boolean
Returns true
if the named file is readable by the real user and group id of this process. See access(3).
Note that some OS-level security features may cause this to return true even though the file is not readable by the real user/group.
1842 1843 1844 1845 1846 |
# File 'file.c', line 1842 static VALUE rb_file_readable_real_p(VALUE obj, VALUE fname) { return RBOOL(rb_access(fname, R_OK) >= 0); } |
.readlink(link_name) ⇒ Object
Returns the name of the file referenced by the given link. Not available on all platforms.
File.symlink("testfile", "link2test") #=> 0
File.readlink("link2test") #=> "testfile"
3114 3115 3116 3117 3118 |
# File 'file.c', line 3114 static VALUE rb_file_s_readlink(VALUE klass, VALUE path) { return rb_readlink(path, rb_filesystem_encoding()); } |
.realdirpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual filesystem.
The real pathname doesn't contain symlinks or useless dots.
If _dir_string_ is given, it is used as a base directory
for interpreting relative pathname instead of the current directory.
The last component of the real pathname can be nonexistent.
4579 4580 4581 4582 4583 4584 4585 4586 |
# File 'file.c', line 4579 static VALUE rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass) { VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil; VALUE path = argv[0]; FilePathValue(path); return rb_realpath_internal(basedir, path, 0); } |
.realpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual
filesystem not containing symlinks or useless dots.
If _dir_string_ is given, it is used as a base directory
for interpreting relative pathname instead of the current directory.
All components of the pathname must exist when this method is
called.
4558 4559 4560 4561 4562 4563 4564 4565 |
# File 'file.c', line 4558 static VALUE rb_file_s_realpath(int argc, VALUE *argv, VALUE klass) { VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil; VALUE path = argv[0]; FilePathValue(path); return rb_realpath_internal(basedir, path, 1); } |
.rename(old_name, new_name) ⇒ 0
Renames the given file to the new name. Raises a SystemCallError if the file cannot be renamed.
File.rename("afile", "afile.bak") #=> 0
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 |
# File 'file.c', line 3230 static VALUE rb_file_s_rename(VALUE klass, VALUE from, VALUE to) { struct rename_args ra; VALUE f, t; FilePathValue(from); FilePathValue(to); f = rb_str_encode_ospath(from); t = rb_str_encode_ospath(to); ra.src = StringValueCStr(f); ra.dst = StringValueCStr(t); #if defined __CYGWIN__ errno = 0; #endif if ((int)(VALUE)rb_thread_call_without_gvl(no_gvl_rename, &ra, RUBY_UBF_IO, 0) < 0) { int e = errno; #if defined DOSISH switch (e) { case EEXIST: if (chmod(ra.dst, 0666) == 0 && unlink(ra.dst) == 0 && rename(ra.src, ra.dst) == 0) return INT2FIX(0); } #endif syserr_fail2(e, from, to); } return INT2FIX(0); } |
.setgid?(file_name) ⇒ Boolean
Returns true
if the named file has the setgid bit set.
file_name can be an IO object.
2147 2148 2149 2150 2151 2152 2153 2154 2155 |
# File 'file.c', line 2147 static VALUE rb_file_sgid_p(VALUE obj, VALUE fname) { #ifdef S_ISGID return check3rdbyte(fname, S_ISGID); #else return Qfalse; #endif } |
.setuid?(file_name) ⇒ Boolean
Returns true
if the named file has the setuid bit set.
file_name can be an IO object.
2128 2129 2130 2131 2132 2133 2134 2135 2136 |
# File 'file.c', line 2128 static VALUE rb_file_suid_p(VALUE obj, VALUE fname) { #ifdef S_ISUID return check3rdbyte(fname, S_ISUID); #else return Qfalse; #endif } |
.size(file_name) ⇒ Integer
Returns the size of file_name
.
file_name can be an IO object.
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 |
# File 'file.c', line 2221 static VALUE rb_file_s_size(VALUE klass, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) { int e = errno; FilePathValue(fname); rb_syserr_fail_path(e, fname); } return OFFT2NUM(st.st_size); } |
.size?(file_name) ⇒ Integer?
Returns nil
if file_name
doesn’t exist or has zero size, the size of the file otherwise.
file_name can be an IO object.
2046 2047 2048 2049 2050 2051 2052 2053 2054 |
# File 'file.c', line 2046 static VALUE rb_file_size_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qnil; if (st.st_size == 0) return Qnil; return OFFT2NUM(st.st_size); } |
.socket?(filepath) ⇒ Boolean
Returns true
if filepath
points to a socket, false
otherwise:
require 'socket'
File.socket?(Socket.new(:INET, :STREAM)) # => true
File.socket?(File.new('t.txt')) # => false
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 |
# File 'file.c', line 1710 static VALUE rb_file_socket_p(VALUE obj, VALUE fname) { #ifndef S_ISSOCK # ifdef _S_ISSOCK # define S_ISSOCK(m) _S_ISSOCK(m) # else # ifdef _S_IFSOCK # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK) # else # ifdef S_IFSOCK # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) # endif # endif # endif #endif #ifdef S_ISSOCK struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; if (S_ISSOCK(st.st_mode)) return Qtrue; #endif return Qfalse; } |
.split(file_name) ⇒ Array
Splits the given string into a directory and a file component and returns them in a two-element array. See also File::dirname and File::basename.
File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
4995 4996 4997 4998 4999 5000 |
# File 'file.c', line 4995 static VALUE rb_file_s_split(VALUE klass, VALUE path) { FilePathStringValue(path); /* get rid of converting twice */ return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef)); } |
.stat(filepath) ⇒ Object
Returns a File::Stat object for the file at filepath
(see File::Stat):
File.stat('t.txt').class # => File::Stat
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 |
# File 'file.c', line 1328 static VALUE rb_file_s_stat(VALUE klass, VALUE fname) { struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (stat_without_gvl(RSTRING_PTR(fname), &st) < 0) { rb_sys_fail_path(fname); } return rb_stat_new(&st); } |
.sticky?(file_name) ⇒ Boolean
Returns true
if the named file has the sticky bit set.
file_name can be an IO object.
2166 2167 2168 2169 2170 2171 2172 2173 2174 |
# File 'file.c', line 2166 static VALUE rb_file_sticky_p(VALUE obj, VALUE fname) { #ifdef S_ISVTX return check3rdbyte(fname, S_ISVTX); #else return Qfalse; #endif } |
.symlink(old_name, new_name) ⇒ 0
Creates a symbolic link called new_name for the existing file old_name. Raises a NotImplemented exception on platforms that do not support symbolic links.
File.symlink("testfile", "link2test") #=> 0
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 |
# File 'file.c', line 3085 static VALUE rb_file_s_symlink(VALUE klass, VALUE from, VALUE to) { FilePathValue(from); FilePathValue(to); from = rb_str_encode_ospath(from); to = rb_str_encode_ospath(to); if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) { sys_fail2(from, to); } return INT2FIX(0); } |
.symlink?(filepath) ⇒ Boolean
Returns true
if filepath
points to a symbolic link, false
otherwise:
symlink = File.symlink('t.txt', 'symlink')
File.symlink?('symlink') # => true
File.symlink?('t.txt') # => false
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 |
# File 'file.c', line 1669 static VALUE rb_file_symlink_p(VALUE obj, VALUE fname) { #ifndef S_ISLNK # ifdef _S_ISLNK # define S_ISLNK(m) _S_ISLNK(m) # else # ifdef _S_IFLNK # define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK) # else # ifdef S_IFLNK # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) # endif # endif # endif #endif #ifdef S_ISLNK struct stat st; FilePathValue(fname); fname = rb_str_encode_ospath(fname); if (lstat_without_gvl(StringValueCStr(fname), &st) < 0) return Qfalse; if (S_ISLNK(st.st_mode)) return Qtrue; #endif return Qfalse; } |
.truncate(file_name, integer) ⇒ 0
Truncates the file file_name to be at most integer bytes long. Not available on all platforms.
f = File.new("out", "w")
f.write("1234567890") #=> 10
f.close #=> nil
File.truncate("out", 5) #=> 0
File.size("out") #=> 5
5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 |
# File 'file.c', line 5120 static VALUE rb_file_s_truncate(VALUE klass, VALUE path, VALUE len) { struct truncate_arg ta; int r; ta.pos = NUM2OFFT(len); FilePathValue(path); path = rb_str_encode_ospath(path); ta.path = StringValueCStr(path); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_truncate, &ta, RUBY_UBF_IO, NULL); if (r < 0) rb_sys_fail_path(path); return INT2FIX(0); } |
.umask ⇒ Integer .umask(integer) ⇒ Integer
Returns the current umask value for this process. If the optional argument is given, set the umask to that value and return the previous value. Umask values are subtracted from the default permissions, so a umask of 0222
would make a file read-only for everyone.
File.umask(0006) #=> 18
File.umask #=> 6
3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 |
# File 'file.c', line 3278 static VALUE rb_file_s_umask(int argc, VALUE *argv, VALUE _) { mode_t omask = 0; switch (argc) { case 0: omask = umask(0); umask(omask); break; case 1: omask = umask(NUM2MODET(argv[0])); break; default: rb_error_arity(argc, 0, 1); } return MODET2NUM(omask); } |
.delete(file_name, ...) ⇒ Integer .unlink(file_name, ...) ⇒ Integer
Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. Since the underlying implementation relies on the unlink(2)
system call, the type of exception raised depends on its error type (see linux.die.net/man/2/unlink) and has the form of e.g. Errno::ENOENT.
See also Dir::rmdir.
3201 3202 3203 3204 3205 |
# File 'file.c', line 3201 static VALUE rb_file_s_unlink(int argc, VALUE *argv, VALUE klass) { return apply2files(unlink_internal, argc, argv, 0); } |
.utime(atime, mtime, file_name, ...) ⇒ Integer
Sets the access and modification times of each named file to the first two arguments. If a file is a symlink, this method acts upon its referent rather than the link itself; for the inverse behavior see File.lutime. Returns the number of file names in the argument list.
2982 2983 2984 2985 2986 |
# File 'file.c', line 2982 static VALUE rb_file_s_utime(int argc, VALUE *argv, VALUE _) { return utime_internal_i(argc, argv, FALSE); } |
.world_readable?(file_name) ⇒ Integer?
If file_name is readable by others, returns an integer representing the file permission bits of file_name. Returns nil
otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2)
.
file_name can be an IO object.
File.world_readable?("/etc/passwd") #=> 420
m = File.world_readable?("/etc/passwd")
sprintf("%o", m) #=> "644"
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 |
# File 'file.c', line 1872 static VALUE rb_file_world_readable_p(VALUE obj, VALUE fname) { #ifdef S_IROTH struct stat st; if (rb_stat(fname, &st) < 0) return Qnil; if ((st.st_mode & (S_IROTH)) == S_IROTH) { return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); } #endif return Qnil; } |
.world_writable?(file_name) ⇒ Integer?
If file_name is writable by others, returns an integer representing the file permission bits of file_name. Returns nil
otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2)
.
file_name can be an IO object.
File.world_writable?("/tmp") #=> 511
m = File.world_writable?("/tmp")
sprintf("%o", m) #=> "777"
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 |
# File 'file.c', line 1936 static VALUE rb_file_world_writable_p(VALUE obj, VALUE fname) { #ifdef S_IWOTH struct stat st; if (rb_stat(fname, &st) < 0) return Qnil; if ((st.st_mode & (S_IWOTH)) == S_IWOTH) { return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO)); } #endif return Qnil; } |
.writable?(file_name) ⇒ Boolean
Returns true
if the named file is writable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the effective user/group.
1897 1898 1899 1900 1901 |
# File 'file.c', line 1897 static VALUE rb_file_writable_p(VALUE obj, VALUE fname) { return RBOOL(rb_eaccess(fname, W_OK) >= 0); } |
.writable_real?(file_name) ⇒ Boolean
Returns true
if the named file is writable by the real user and group id of this process. See access(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the real user/group.
1914 1915 1916 1917 1918 |
# File 'file.c', line 1914 static VALUE rb_file_writable_real_p(VALUE obj, VALUE fname) { return RBOOL(rb_access(fname, W_OK) >= 0); } |
.zero?(file_name) ⇒ Boolean
Returns true
if the named file exists and has a zero size.
file_name can be an IO object.
2027 2028 2029 2030 2031 2032 2033 2034 |
# File 'file.c', line 2027 static VALUE rb_file_zero_p(VALUE obj, VALUE fname) { struct stat st; if (rb_stat(fname, &st) < 0) return Qfalse; return RBOOL(st.st_size == 0); } |
Instance Method Details
#atime ⇒ Time
Returns the last access time (a Time object) for file, or epoch if file has not been accessed.
File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 |
# File 'file.c', line 2340 static VALUE rb_file_atime(VALUE obj) { rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return stat_atime(&st); } |
#birthtime ⇒ Time
Returns the birth time for file.
File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003
If the platform doesn’t have birthtime, raises NotImplementedError.
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 |
# File 'file.c', line 2500 static VALUE rb_file_birthtime(VALUE obj) { rb_io_t *fptr; statx_data st; GetOpenFile(obj, fptr); if (fstatx_without_gvl(fptr->fd, &st, STATX_BTIME) == -1) { rb_sys_fail_path(fptr->pathv); } return statx_birthtime(&st, fptr->pathv); } |
#chmod(mode_int) ⇒ 0
Changes permission bits on file to the bit pattern represented by mode_int. Actual effects are platform dependent; on Unix systems, see chmod(2)
for details. Follows symbolic links. Also see File#lchmod.
f = File.new("out", "w");
f.chmod(0644) #=> 0
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 |
# File 'file.c', line 2598 static VALUE rb_file_chmod(VALUE obj, VALUE vmode) { rb_io_t *fptr; mode_t mode; #if !defined HAVE_FCHMOD || !HAVE_FCHMOD VALUE path; #endif mode = NUM2MODET(vmode); GetOpenFile(obj, fptr); #ifdef HAVE_FCHMOD if (fchmod(fptr->fd, mode) == -1) { if (HAVE_FCHMOD || errno != ENOSYS) rb_sys_fail_path(fptr->pathv); } else { if (!HAVE_FCHMOD) return INT2FIX(0); } #endif #if !defined HAVE_FCHMOD || !HAVE_FCHMOD if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (chmod(RSTRING_PTR(path), mode) == -1) rb_sys_fail_path(fptr->pathv); #endif return INT2FIX(0); } |
#chown(owner_int, group_int) ⇒ 0
Changes the owner and group of file to the given numeric owner and group id’s. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file’s group to any group to which the owner belongs. A nil
or -1 owner or group id is ignored. Follows symbolic links. See also File#lchown.
File.new("testfile").chown(502, 1000)
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 |
# File 'file.c', line 2732 static VALUE rb_file_chown(VALUE obj, VALUE owner, VALUE group) { rb_io_t *fptr; rb_uid_t o; rb_gid_t g; #ifndef HAVE_FCHOWN VALUE path; #endif o = to_uid(owner); g = to_gid(group); GetOpenFile(obj, fptr); #ifndef HAVE_FCHOWN if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (chown(RSTRING_PTR(path), o, g) == -1) rb_sys_fail_path(fptr->pathv); #else if (fchown(fptr->fd, o, g) == -1) rb_sys_fail_path(fptr->pathv); #endif return INT2FIX(0); } |
#ctime ⇒ Time
Returns the change time for file (that is, the time directory information about the file was changed, not the file itself).
Note that on Windows (NTFS), returns creation time (birth time).
File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 |
# File 'file.c', line 2443 static VALUE rb_file_ctime(VALUE obj) { rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return stat_ctime(&st); } |
#flock(operation) ⇒ Object
:markup: markdown
call-seq:
flock(locking_constant) -> 0 or false
Locks or unlocks a file according to the given ‘locking_constant`, a bitwise OR of the values in the table below.
Not available on all platforms.
Returns ‘false` if `File::LOCK_NB` is specified and the operation would have blocked; otherwise returns `0`.
<table>
<tr>
<th colspan="3">Locking Constants</th>
</tr>
<tr>
<th>Constant</th>
<th>Lock</th>
<th>Effect</th>
</tr>
<tr>
<td><tt>File::LOCK_EX</tt></td>
<td>Exclusive</td>
<td>Only one process may hold an exclusive lock for <tt>self</tt> at a time.</td>
</tr>
<tr>
<td><tt>File::LOCK_NB</tt></td>
<td>Non-blocking</td>
<td>
No blocking; may be combined with other <tt>File::LOCK_SH</tt> or <tt>File::LOCK_EX</tt>
using the bitwise OR operator <tt>|</tt>.
</td>
</tr>
<tr>
<td><tt>File::LOCK_SH</tt></td>
<td>Shared</td>
<td>Multiple processes may each hold a shared lock for <tt>self</tt> at the same time.</td>
</tr>
<tr>
<td><tt>File::LOCK_UN</tt></td>
<td>Unlock</td>
<td>Remove an existing lock held by this process.</td>
</tr>
</table>
Example:
“‘ruby # Update a counter using an exclusive lock. # Don’t use File::WRONLY because it truncates the file. File.open(‘counter’, File::RDWR | File::CREAT, 0644) do |f|
f.flock(File::LOCK_EX)
value = f.read.to_i + 1
f.rewind
f.write("#{value}\n")
f.flush
f.truncate(f.pos)
end
# Read the counter using a shared lock. File.open(‘counter’, ‘r’) do |f|
f.flock(File::LOCK_SH)
f.read
end “‘
5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 |
# File 'file.c', line 5297 static VALUE rb_file_flock(VALUE obj, VALUE operation) { rb_io_t *fptr; int op[2], op1; struct timeval time; op[1] = op1 = NUM2INT(operation); GetOpenFile(obj, fptr); op[0] = fptr->fd; if (fptr->mode & FMODE_WRITABLE) { rb_io_flush_raw(obj, 0); } while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) { int e = errno; switch (e) { case EAGAIN: case EACCES: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif if (op1 & LOCK_NB) return Qfalse; time.tv_sec = 0; time.tv_usec = 100 * 1000; /* 0.1 sec */ rb_thread_wait_for(time); rb_io_check_closed(fptr); continue; case EINTR: #if defined(ERESTART) case ERESTART: #endif break; default: rb_syserr_fail_path(e, fptr->pathv); } } return INT2FIX(0); } |
#lstat ⇒ Object
Like File#stat, but does not follow the last symbolic link; instead, returns a File::Stat object for the link itself:
File.symlink('t.txt', 'symlink')
f = File.new('symlink')
f.stat.size # => 47
f.lstat.size # => 11
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
# File 'file.c', line 1434 static VALUE rb_file_lstat(VALUE obj) { #ifdef HAVE_LSTAT rb_io_t *fptr; struct stat st; VALUE path; GetOpenFile(obj, fptr); if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (lstat_without_gvl(RSTRING_PTR(path), &st) == -1) { rb_sys_fail_path(fptr->pathv); } return rb_stat_new(&st); #else return rb_io_stat(obj); #endif } |
#mtime ⇒ Time
Returns the modification time for file.
File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 |
# File 'file.c', line 2388 static VALUE rb_file_mtime(VALUE obj) { rb_io_t *fptr; struct stat st; GetOpenFile(obj, fptr); if (fstat(fptr->fd, &st) == -1) { rb_sys_fail_path(fptr->pathv); } return stat_mtime(&st); } |
#size ⇒ Integer
Returns the size of file in bytes.
File.new("testfile").size #=> 66
2549 2550 2551 2552 2553 |
# File 'file.c', line 2549 static VALUE file_size(VALUE self) { return OFFT2NUM(rb_file_size(self)); } |
#truncate(integer) ⇒ 0
Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.
f = File.new("out", "w")
f.syswrite("1234567890") #=> 10
f.truncate(5) #=> 0
f.close() #=> nil
File.size("out") #=> 5
5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 |
# File 'file.c', line 5169 static VALUE rb_file_truncate(VALUE obj, VALUE len) { rb_io_t *fptr; struct ftruncate_arg fa; fa.pos = NUM2OFFT(len); GetOpenFile(obj, fptr); if (!(fptr->mode & FMODE_WRITABLE)) { rb_raise(rb_eIOError, "not opened for writing"); } rb_io_flush_raw(obj, 0); fa.fd = fptr->fd; if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) { rb_sys_fail_path(fptr->pathv); } return INT2FIX(0); } |