class File
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:
# English text with newlines. text = <<~EOT First line Second line Fourth line Fifth line EOT # Russian text. russian = "\u{442 435 441 442}" # => "ΡΠ΅ΡΡ" # Binary data. data = "\u9990\u9991\u9992\u9993\u9994" # Text file. File.write('t.txt', text) # File with Russian text. File.write('t.rus', russian) # File with binary data. f = File.new('t.dat', 'wb:UTF-16') f.write(data) f.close
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:
-
Anywheremeans that methodsIO#rewind,IO#pos=, andIO#seekmay be used to change the fileβs position, so that allowed reading or writing may occur anywhere in the file. -
End onlymeans that writing can occur only at end-of-file, and that methodsIO#rewind,IO#pos=, andIO#seekdo not affect writing. -
Errormeans that an exception is raised if disallowed reading or writing is attempted.
Read/Write Modes for Existing File
-
'r':-
Fileis 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
-
Filemay be read anywhere; seeIO#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':-
Fileis 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
-
Filemay be written anywhere (even past end-of-file); seeIO#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':-
Fileis 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
-
Filemay be written only at end-of-file;IO#rewind,IO#pos=,IO#seekdo 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+':-
Fileis 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
-
Filemay be read or written anywhere (even past end-of-file); seeIO#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+':-
Fileis 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
-
Filemay be written only at end-of-file;IO#rewind,IO#pos=,IO#seekdo 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"
-
Filemay be read anywhere; seeIO#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
-
Filemay be written anywhere (even past end-of-file); seeIO#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
-
Filemay be written anywhere (even past end-of-file); seeIO#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
-
Filemay be read anywhere (even past end-of-file); seeIO#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"
-
Filemay be read anywhere (even past end-of-file); seeIO#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 interpreting0x1Aas 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 interpreting0x1Aas 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::CREATis 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 asto_path): Returns the string representation of the given path.
Times
-
::atime: Returns aTimefor the most recent access to the given file. -
::birthtime: Returns aTimefor the creation of the given file. -
::ctime: Returns aTimefor the metadata change of the given file. -
::mtime: Returns aTimefor the most recent data modification to the content of the given file. -
mtime: Returns aTimefor the most recent data modification to the content ofself.
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 theFile::Statobject 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 theFile::Statobject 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 theFile::Statobject for the last symbolic link in the path forself.
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?: Returnsnilif 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) ofself.
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 unlocksself.
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: Truncatesselfto the given size.
Public Class Methods
(path file_name, ?path dir_string) → String
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 888
def self.absolute_path: (path file_name, ?path dir_string) -> String
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"
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 898
def self.absolute_path?: (path file_name) -> bool
Returns true if file_name is an absolute path, and false otherwise.
File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 910
def self.atime: (path | IO file_name) -> Time
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 926
def self.basename: (path file_name, ?string suffix) -> String
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"
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 940
def self.birthtime: (path | IO 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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 951
def self.blockdev?: (path | IO file_name) -> bool
Returns true if filepath points to a block device, false otherwise:
File.blockdev?('/dev/sda1') # => true File.blockdev?(File.new('t.tmp')) # => false
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 962
def self.chardev?: (path | IO file_name) -> bool
Returns true if filepath points to a character device, false otherwise.
File.chardev?($stdin) # => true File.chardev?('t.txt') # => false
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 975
def self.chmod: (int mode, *path 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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 989
def self.chown: (int? owner, int? group, *path 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")
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1004
def self.ctime: (path | IO 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
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.
(path | IO path) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1037
def self.directory?: (path | IO path) -> bool
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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1055
def self.dirname: (path file_name, ?Integer level) -> String
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) #=> "/"
Returns true if the named file exists and has a zero size.
file_name can be an IO object.
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1081
def self.executable?: (path file_name) -> bool
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.
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1097
def self.executable_real?: (path file_name) -> bool
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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1109
def self.exist?: (path | IO file_name) -> bool
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.
(path file_name, ?path dir_string) → String
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1136
def self.expand_path: (path file_name, ?path dir_string) -> String
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 <code>~β, which expands to the process ownerβs home directory (the environment variable HOME must be set correctly). </code>~userβ expands to the named userβs home directory.
File.expand_path("~oracle/bin") #=> "/home/oracle/bin"
A simple example of using dir_string is as follows. File.expand_path(β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.expand_path("../../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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1162
def self.extname: (path 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"
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1175
def self.file?: (path | IO file) -> bool
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.
(string pattern, path path, ?int flags) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1279
def self.fnmatch: (string pattern, path path, ?int flags) -> bool
Returns true if path matches against pattern. The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:
<em> : Matches any file. Can be restricted by other values in the glob. Equivalent to /.</em>/x in regexp.
<code>*</code>
: Matches all regular files
<code>c*</code>
: Matches all files beginning with c
<code>*c</code>
: Matches all files ending with c
<code>*c*</code>
: Matches all files that have c in them (including at the beginning or end).
To match hidden files (that start with a <code>.</code>) set the File::FNM_DOTMATCH flag.
** : Matches directories recursively or files expansively.
? : Matches any one character. Equivalent to /.{1}/ in regexp.
[set] : Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ({*1}[rdoc-label:foottext-1:footmark-1]).
<code></code> : Escapes the next metacharacter.
{a,b} : Matches pattern a and pattern b if File::FNM_EXTGLOB flag is enabled. Behaves like a Regexp union ((?:a|b)).
flags is a bitwise OR of the FNM_XXX constants. The same glob pattern and flags are used by Dir::glob.
Examples:
File.fnmatch('cat', 'cat') #=> true # match entire string File.fnmatch('cat', 'category') #=> false # only match partial string File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported by default File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true # { } is supported on FNM_EXTGLOB File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character File.fnmatch('c??t', 'cat') #=> false # ditto File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!') File.fnmatch('cat', 'CAT') #=> false # case sensitive File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive File.fnmatch('cat', 'CAT', File::FNM_SYSCASE) #=> true or false # depends on the system default File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESCAPE makes '\' ordinary File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default. File.fnmatch('.*', '.profile') #=> true File.fnmatch('**/*.rb', 'main.rb') #=> false File.fnmatch('**/*.rb', './main.rb') #=> false File.fnmatch('**/*.rb', 'lib/song.rb') #=> true File.fnmatch('**.rb', 'main.rb') #=> true File.fnmatch('**.rb', './main.rb') #=> false File.fnmatch('**.rb', 'lib/song.rb') #=> true File.fnmatch('*', 'dave/.profile') #=> true File.fnmatch('**/foo', 'a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch('**/foo', '/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch('**/foo', 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true File.fnmatch('**/foo', 'a/.b/c/foo', File::FNM_PATHNAME) #=> false File.fnmatch('**/foo', 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1300
def self.ftype: (path 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"
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1311
def self.grpowned?: (path | IO file_name) -> bool
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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1331
def self.identical?: (path | IO file_1, path | IO file_2) -> bool
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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1341
def self.join: (*path) -> String
Returns a new string formed by joining the strings using "/".
File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1351
def self.lchmod: (int mode, *path 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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1361
def self.lchown: (int? owner, int? group, *path 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.
(path old_name, path new_name) → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1374
def self.link: (path old_name, path 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"
(path file_name) → File::Stat
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1387
def self.lstat: (path file_name) -> File::Stat
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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1398
def self.lutime: (Time | Numeric atime, Time | Numeric mtime, *path 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.
(path file_name, ?int mode) → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1408
def self.mkfifo: (path file_name, ?int mode) -> 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).
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1420
def self.mtime: (path | IO file_name) -> Time
(path | int file_name, ?string | int mode, ?int perm, ?mode: Integer | String, ?flags: Integer, ?external_encoding: encoding, ?internal_encoding: encoding, ?encoding: encoding, ?textmode: boolish, ?binmode: boolish, ?autoclose: boolish, ?path: path, ?invalid: :replace | nil, ?undef: :replace | nil, ?replace: String | nil, ?fallback: Hash[string, string] | ^(String) → string | Method | nil, ?xml: :text | :attr | nil, ?cr_newline: bool, ?crlf_newline: bool, ?universal_newline: bool) → void
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 851
def initialize: (
path | int file_name,
?string | int mode,
?int perm,
# open options
?mode: Integer | String,
?flags: Integer,
?external_encoding: encoding,
?internal_encoding: encoding,
?encoding: encoding,
?textmode: boolish,
?binmode: boolish,
?autoclose: boolish,
?path: path,
# encoding options
?invalid: :replace | nil,
?undef: :replace | nil,
?replace: String | nil,
?fallback: Hash[string, string] | ^(String) -> string | Method | nil,
?xml: :text | :attr | nil,
?cr_newline: bool,
?crlf_newline: bool,
?universal_newline: bool
) -> void
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:
-
Encoding options.
(path | int file_name, ?string | int mode, ?int perm, ?mode: Integer | String, ?flags: Integer, ?external_encoding: encoding, ?internal_encoding: encoding, ?encoding: encoding, ?textmode: boolish, ?binmode: boolish, ?autoclose: boolish, ?path: path, ?invalid: :replace | nil, ?undef: :replace | nil, ?replace: String | nil, ?fallback: Hash[string, string] | ^(String) → string | Method | nil, ?xml: :text | :attr | nil, ?cr_newline: bool, ?crlf_newline: bool, ?universal_newline: bool) → instance
[T] (path | int file_name, ?string | int mode, ?int perm, ?mode: Integer | String, ?flags: Integer, ?external_encoding: encoding, ?internal_encoding: encoding, ?encoding: encoding, ?textmode: boolish, ?binmode: boolish, ?autoclose: boolish, ?path: path, ?invalid: :replace | nil, ?undef: :replace | nil, ?replace: String | nil, ?fallback: Hash[string, string] | ^(String) → string | Method | nil, ?xml: :text | :attr | nil, ?cr_newline: bool, ?crlf_newline: bool, ?universal_newline: bool) { (File) → T } → T
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1434
def self.open: (
path | int file_name,
?string | int mode,
?int perm,
# open options
?mode: Integer | String,
?flags: Integer,
?external_encoding: encoding,
?internal_encoding: encoding,
?encoding: encoding,
?textmode: boolish,
?binmode: boolish,
?autoclose: boolish,
?path: path,
# encoding options
?invalid: :replace | nil,
?undef: :replace | nil,
?replace: String | nil,
?fallback: Hash[string, string] | ^(String) -> string | Method | nil,
?xml: :text | :attr | nil,
?cr_newline: bool,
?crlf_newline: bool,
?universal_newline: bool
) -> instance
| [T] (
path | int file_name,
?string | int mode,
?int perm,
# open options
?mode: Integer | String,
?flags: Integer,
?external_encoding: encoding,
?internal_encoding: encoding,
?encoding: encoding,
?textmode: boolish,
?binmode: boolish,
?autoclose: boolish,
?path: path,
# encoding options
?invalid: :replace | nil,
?undef: :replace | nil,
?replace: String | nil,
?fallback: Hash[string, string] | ^(String) -> string | Method | nil,
?xml: :text | :attr | nil,
?cr_newline: bool,
?crlf_newline: bool,
?universal_newline: bool
) { (File) -> T } -> T
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1492
def self.owned?: (path | IO file_name) -> bool
Returns true if the named file exists and the effective user id of the calling process is the owner of the file.
file_name can be an IO object.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1520
def self.path: (path path) -> String
Returns the string representation of the path
File.path(File::NULL) #=> "/dev/null" File.path(Pathname.new("/tmp")) #=> "/tmp"
If path is not a String:
-
If it has the
to_pathmethod, that method will be called to coerce to aString. -
Otherwise, or if the coerced result is not a
Stringtoo, the standard coersion usingto_strmethod will take place on that object. (See alsoString.try_convert)
The coerced string must satisfy the following conditions:
-
It must be in an ASCII-compatible encoding; otherwise, an
Encoding::CompatibilityErroris raised. -
It must not contain the NUL character (
\0); otherwise, anArgumentErroris raised.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1532
def self.pipe?: (path | IO file_name) -> bool
Returns true if filepath points to a pipe, false otherwise:
File.mkfifo('tmp/fifo') File.pipe?('tmp/fifo') # => true File.pipe?('t.txt') # => false
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1544
def self.readable?: (path file_name) -> bool
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.
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1556
def self.readable_real?: (path file_name) -> bool
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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1568
def self.readlink: (path link_name) -> String
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"
(path pathname, ?path dir_string) → String
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1582
def self.realdirpath: (path pathname, ?path dir_string) -> String
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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1596
def self.realpath: (path pathname, ?path dir_string) -> String
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.
(path old_name, path new_name) → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1607
def self.rename: (path old_name, path 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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1617
def self.setgid?: (path | IO file_name) -> bool
Returns true if the named file has the setgid bit set.
file_name can be an IO object.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1627
def self.setuid?: (path | IO file_name) -> bool
Returns true if the named file has the setuid bit set.
file_name can be an IO object.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1637
def self.size: (path | IO file_name) -> Integer
Returns the size of file_name.
file_name can be an IO object.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1648
def self.size?: (path | IO 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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1660
def self.socket?: (path | IO file_name) -> bool
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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1671
def self.split: (path file_name) -> [ String, String ]
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"]
(path file_name) → File::Stat
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1681
def self.stat: (path file_name) -> File::Stat
Returns a File::Stat object for the file at filepath (see File::Stat):
File.stat('t.txt').class # => File::Stat
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1691
def self.sticky?: (path | IO file_name) -> bool
Returns true if the named file has the sticky bit set.
file_name can be an IO object.
(path old_name, path new_name) → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1703
def self.symlink: (path old_name, path 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
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1715
def self.symlink?: (path file_name) -> bool
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
(path file_name, int length) → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1730
def self.truncate: (path file_name, int length) -> 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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1745
def self.umask: (?int umask) -> 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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1760
def self.unlink: (*path 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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1771
def self.utime: (Time | Numeric atime, Time | Numeric mtime, *path 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.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1787
def self.world_readable?: (path | IO 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"
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1803
def self.world_writable?: (path | IO 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"
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1815
def self.writable?: (path file_name) -> bool
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.
(path file_name) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1827
def self.writable_real?: (path file_name) -> bool
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.
Public Instance Methods
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1848
def 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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1860
def 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.
(int mode) → (0 | nil)
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1874
def chmod: (int mode) -> (0 | nil)
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
(int? owner, int? group) → (0 | nil)
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1888
def chown: (int? owner, int? group) -> (0 | nil)
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)
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1901
def 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
(int locking_constant) → (0 | false)
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1937
def flock: (int locking_constant) -> (0 | false)
Locks or unlocks file +self+ 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. Constant | Lock | Effect βββββ|ββββ|ββββββββββββββββββββββββββββββββββββββ +File::LOCK_EX+| Exclusive | Only one process may hold an exclusive lock for +self+ at a time. +File::LOCK_NB+|Non-blocking|No blocking; may be combined with +File::LOCK_SH+ or +File::LOCK_EX+ using the bitwise OR operator |. +File::LOCK_SH+| Shared | Multiple processes may each hold a shared lock for +self+ at the same time. +File::LOCK_UN+| Unlock | Remove an existing lock held by this process. Example: # 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
() → (File::Stat | nil)
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1951
def lstat: () -> (File::Stat | nil)
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
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1961
def mtime: () -> Time
Returns the modification time for file.
File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1980
def path: () -> String
Returns the pathname used to create file as a string. Does not normalize the name.
The pathname may not point to the file corresponding to file. For instance, the pathname becomes void when the file has been moved or deleted.
This method raises IOError for a file created using File::Constants::TMPFILE because they donβt have a pathname.
File.new("testfile").path #=> "testfile" File.new("/tmp/../tmp/xxx", "w").path #=> "/tmp/../tmp/xxx"
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 1990
def size: () -> Integer
Returns the size of file in bytes.
File.new("testfile").size #=> 66
Returns the pathname used to create file as a string. Does not normalize the name.
The pathname may not point to the file corresponding to file. For instance, the pathname becomes void when the file has been moved or deleted.
This method raises IOError for a file created using File::Constants::TMPFILE because they donβt have a pathname.
File.new("testfile").path #=> "testfile" File.new("/tmp/../tmp/xxx", "w").path #=> "/tmp/../tmp/xxx"
(int length) → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/core/file.rbs, line 2020
def truncate: (int length) -> 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