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

# Japanese text.
japanese = 'こんにちは'

# Binary data.
data = "\u9990\u9991\u9992\u9993\u9994"

# Text file.
File.write('t.txt', text)

# File with Japanese text.
File.write('t.ja', japanese)

# 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:

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 to Encoding::UTF_8; on Windows, enables conversion between EOL and CRLF and enables interpreting 0x1A as an end-of-file marker.

  • 'b': Binary data; sets the default external encoding to Encoding::ASCII_8BIT; on Windows, suppresses conversion between EOL and CRLF and disables interpreting 0x1A 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 if File::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.

Constants

ALT_SEPARATOR

platform specific alternative separator

PATH_SEPARATOR

path list separator

SEPARATOR

separates directory parts in path

Separator

separates directory parts in path

Public Class Methods

Returns the string absolute path for the given path.

Evaluates a relative path with respect to the directory given by dirpath:

Dir.chdir('/snap')
# Default dirpath.
File.absolute_path('README')                  # => "/snap/README"
File.absolute_path('bin')                     # => "/snap/bin"
File.absolute_path('bin/../var')              # => "/snap/var"
# Other dirpath.
File.absolute_path('../zip', '/usr/bin/ruby') # => "/usr/bin/zip"

For an absolute path, argument dirpath is ignored:

File.absolute_path('/snap', '/usr/bin')       # => "/snap"
File.absolute_path('/snap', 'nosuch')         # => "/snap"

A leading tilde character ('~'), is not expanded:

Dir.chdir('/usr/bin')
File.absolute_path("~")                       # => "/usr/bin/~"
File.absolute_path("~/Documents")             # => "/usr/bin/~/Documents"
static VALUE
s_absolute_path(int c, const VALUE * v, VALUE _)
{
    return rb_file_s_absolute_path(c, v);
}

Returns whether the given path is an absolute path:

File.absolute_path?('/home') # => true
File.absolute_path?('lib')   # => false

The result is OS-dependent for some paths:

File.absolute_path?('C:/')   # => true   # On Windows.
File.absolute_path?('C:/')   # => false  # Elsewhere.
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;
}

Returns a new Time object containing the time of the most recent access to the given object. See File System Timestamps.

Access time for a file is established when it is created, and may be updated when the file content is read:

filepath = '/tmp/t.tmp'
File.exist?(filepath)       # => false
File.atime(filepath)        # Raises Errno::ENOENT: No such file or directory.
File.write(filepath, 'foo') # Establishes access time.
File.atime(filepath)        # => 2026-10-04 14:23:12.421395099 -0500
File.read(filepath)         # Updates access time.
File.atime(filepath)        # => 2026-10-04 14:23:21.848886816 -0500
File.delete(filepath)       # Clean up.

Access time for a directory is established when it is created, and may updated when its entries are read:

dirpath = '/tmp/foo'
File.exist?(dirpath) # => false
File.atime(dirpath)  # Raises Errno::ENOENT: No such file or directory.
Dir.mkdir(dirpath)   # Establishes access time.
File.atime(dirpath)  # => 2026-10-04 14:35:53.940716253 -0500
Dir.entries(dirpath) # Updates access time.
File.atime(dirpath)  # => 2026-10-04 14:36:24.316018872 -0500
Dir.rmdir(dirpath)   # Clean up.

Argument object may be a string path (as above), a File object, or a Dir object:

File.atime(File.new('/etc/passwd')) # => 2026-10-04 11:25:01.259278928 -0500
File.atime('.')                     # => 2026-10-04 14:40:42.141637825 -0500
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_time(stat_atimespec(&st));
}

Returns a new string containing all or part of the last component of the given path. Components are delimited by the value of constant File::SEPARATOR and, if non-nil, the value of constant File::ALT_SEPARATOR.

When suffix is the empty string '', returns all of the last entry:

File.basename('foo/bar/baz/bat.txt') # => "bat.txt"
File.basename('foo/bar/baz')         # => "baz"

File::SEPARATOR                      # => "/"
File.basename('foo/bar.txt////')     # => "bar.txt"
File::ALT_SEPARATOR                  # => "\\"  # On Windows.
File.basename('foo/bar.txt//\\\\//') # => "bar.txt"

When suffix is '.*', the last filename extension, if any, is removed:

File.basename('foo/bar.txt', '.*')     # => "bar"
File.basename('foo/bar.txt.old', '.*') # => "bar.txt"
File.basename('foo/bar', '.*')         # => "bar"

When suffix is any string other than '' or '.*', the matching trailing substring, if any, is removed:

File.basename('foo/bar.txt', '.txt') # => "bar"
File.basename('foo/bar.txt', 'txt')  # => "bar."
File.basename('foo/bar.txt', '*')    # => "bar.txt"
File.basename('foo/bar.txt', '.')    # => "bar.txt"
static VALUE
rb_file_s_basename(int argc, VALUE *argv, VALUE _)
{
    VALUE fname, fext = Qnil;
    const char *name, *p, *fp = 0;
    rb_len_t f = 0, n;
    rb_encoding *enc;

    argc = rb_check_arity(argc, 1, 2);
    fname = argv[0];
    CheckPath(fname, name);
    if (argc == 2) {
        fext = argv[1];
        fp = StringValueCStr(fext);
        check_path_encoding(fext);
    }
    if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
        enc = rb_str_enc_get(fname);
    }

    n = RSTRING_LEN(fname);
    if (n <= 0 || !*name) {
        return rb_enc_str_new(0, 0, enc);
    }

    bool mb_enc = enc_mbclen_needed(enc);
    p = enc_find_basename(name, &f, &n, mb_enc, enc);
    if (n >= 0) {
        if (!fp) {
            f = n;
        }
        else {
            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);
        }
    }

    return rb_enc_str_new(p, f, enc);
}

Returns a new Time object containing the creation time of the entry at the given path; see File System Timestamps:

filepath = '/tmp/t.tmp'
File.birthtime(filepath) # Raises Errno::ENOENT: No such file or directory.
File.write(filepath, 'foo')
File.birthtime(filepath) # => 2026-10-05 13:41:02.330337383 -0500
File.delete(filepath)    # Clean up.
static VALUE
rb_file_s_birthtime(VALUE klass, VALUE fname)
{
    rb_io_stat_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);
}

Returns whether object (a path or IO object) represents a block device (i.e., a direct-access device):

File.blockdev?('/dev/nvme0n1') # => true
File.blockdev?('/dev/loop0')   # => true
File.blockdev?('/dev/tty')     # => false
File.blockdev?('/dev/null')    # => false
File.blockdev?('nosuch')       # => false
File.blockdev?($stdin)         # => false

The returned value is filesystem-dependent; returns false on Windows or MacOS.

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;
}

Returns whether object (a path or IO object) represents a character device (i.e., a sequential-access device):

File.chardev?('/dev/tty')     # => true
File.chardev?('/dev/null')    # => true
File.chardev?($stdin)         # => true
File.chardev?('/dev/nvme0n1') # => false
File.chardev?('/dev/loop0')   # => false
File.chardev?('nosuch')       # => false

The returned value is filesystem-dependent; on Windows, always false.

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;
}

Changes the modes of each of the entries at each the given paths; returns the count of the given paths. See Filesystem Modes and especially Filesystem Modes.

file0path = '/tmp/t0.tmp'
file1path = '/tmp/t1.tmp'
File.write(file0path, 'foo')
File.write(file1path, 'bar')
'%06o' % File.stat(file0path).mode # => "100664"
'%06o' % File.stat(file1path).mode # => "100664"
File.chmod(0o755, file0path, file1path)
'%06o' % File.stat(file0path).mode # => "100755"
'%06o' % File.stat(file1path).mode # => "100755"
File.delete(file0path, file1path)  # Clean up.
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);
}

Changes the owner and group of the entry at each of the given paths; returns the count of the given paths:

# Super user; all privileges.
Process.uid                               => 0
Process.gid                               => 0
# Create a directory and a file.
dirpath = 'doc/foo'
Dir.mkdir(dirpath)
filepath = 't.tmp'
File.write(filepath, 'foo')
# Get their user and group ids.
dirstat = File::Stat.new(dirpath)
dirstat.uid                               => 0
dirstat.gid                               => 0
filestat = File::Stat.new(filepath)
filestat.uid                              => 0
filestat.gid                              => 0
# Change ownership of both.
File.chown(1000, 1000, filepath, dirpath) => 2
dirstat = File::Stat.new(dirpath)
dirstat.uid                               => 1000
dirstat.gid                               => 1000
filestat = File::Stat.new(filepath)
filestat.uid                              => 1000
filestat.gid                              => 1000
# Clean up.
Dir.rmdir(dirpath)
File.delete(filepath)

Notes:

  • On Windows, the owner and group are not changed.

  • Only a process with superuser privileges can change the owner of an entry.

  • The owner of an entry can change its group to any group to which the owner belongs.

  • A nil or -1 owner or group id is ignored.

  • The method follows symbolic links to the target entry.

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);
}

On Windows, returns the birthtime for object.

On other systems, returns a new Time object containing the time of the most recent metadata change to the entry represented by object, which is a string path or an IO object; see File System Timestamps:

dirpath = '/tmp/dir'
Dir.mkdir(dirpath)
File.ctime(dirpath)                    # => 2026-10-05 16:24:40.347201215 -0500
# Create file therein; file ctime established; directory ctime updated.
filepath = File.join(dirpath, 't.tmp') # => "/tmp/dir/t.tmp"
File.write(filepath, 'foo')
File.ctime(dirpath)                    # => 2026-10-05 16:25:34.790762181 -0500
File.ctime(filepath)                   # => 2026-10-05 16:25:34.790762181 -0500
# Write file; file ctime updated; directory ctime not updated.
File.write(filepath, 'bar')
File.ctime(dirpath)                    # => 2026-10-05 16:25:34.790762181 -0500
File.ctime(filepath)                   # => 2026-10-05 16:26:23.030432041 -0500
# Read file; neither ctime updated.
File.read(filepath)
File.ctime(dirpath)                    # => 2026-10-05 16:25:34.790762181 -0500
File.ctime(filepath)                   # => 2026-10-05 16:26:23.030432041 -0500
FileUtils.rm_rf(dirpath)               # Clean up.
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_time(stat_ctimespec(&st));
}

Removes the entry (hard link) at each path in paths; returns the count of removed entries:

filepath0 = '/tmp/t0.tmp'
filepath1 = '/tmp/t1.tmp'
File.write(filepath0, 'foo')
File.write(filepath1, 'bar')
File.unlink(filepath0, filepath1) # => 2

If the removed hard link is the last one associated with the inode, also removes the inode; otherwise, not. See hard link.

Does not follow symbolic links; if the entry is a symbolic link, removes the entry itself (not the link target).

filepath = '/tmp/t.tmp'
linkpath = '/tmp/link'
File.write(filepath, 'foo')
File.symlink(filepath, linkpath)
File.unlink(linkpath) # => 1
File.exist?(filepath) # => true
File.unlink(filepath) # => 1

Raises an exception on any error; some entries may have been deleted before the error occurs.

static VALUE
rb_file_s_unlink(int argc, VALUE *argv, VALUE klass)
{
    return apply2files(unlink_internal, argc, argv, 0);
}

Returns whether the given object represents a directory; object may be a string path or an IO object:

File.directory?('/etc')        # => true
File.directory?('/etc/passwd') # => false
File.directory?($stdin)        # => false
File.directory?('nosuch')      # => false
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;
}

Returns a string path containing all but the last count components of the given path:

File.dirname('/usr/lib/linux')     # => "/usr/lib"
File.dirname('/usr')               # => "/"
File.dirname('/')                  # => "/"
File.dirname('lib/')               # => "."
File.dirname('nosuch')             # => "."
File.dirname('/usr/lib/linux', 2)  # => "/usr"
File.dirname('/usr/lib/linux', 20) # => "/"
File.dirname('/usr/lib/linux', 0)  # => "/usr/lib/linux"

Components are delimited by File::SEPARATOR and, if non-nil, File::ALT_SEPARATOR.

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);
}

Returns whether the given object exists and has size zero.

The given object may be the path to a file:

filepath = '/tmp/t.tmp'
File.write(filepath, 'foo') # File has non-zero size.
File.zero?(filepath)        # => false
File.truncate(filepath, 0)  # File has zero size.
File.zero?(filepath)        # => true
File.delete(filepath)       # Clean up.

The given object may be the path to a directory:

dirpath = '/tmp/foo'
Dir.mkdir(dirpath)
Dir.new(dirpath).children.size # => 0
# Size is filesystem-dependent; may or may not be zero.
File.size(dirpath)             # => 4096
File.zero?(dirpath)            # => false
filepath = '/tmp/foo/t.tmp'    # => "/tmp/foo/t.tmp"
File.write(filepath, 'foo')    # Add a child.
Dir.new(dirpath).children.size # => 1
File.size(dirpath)             # => 4096
File.zero?(dirpath)            # => false
FileUtils.rm_rf(dirpath)       # Clean up.

The given object may be an IO object:

File.zero?($stdin) # => true

The given object may be none of the above:

File.zero?('nosuch') # => false
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);
}

Returns whether the filesystem entry at the given path is executable by the effective owner/group of the current process:

File.executable?('/bin/ruby')   # => true
File.executable?('/etc')        # => true
File.executable?('/etc/passwd') # => false
File.executable?('nosuch')      # => false

Note that some filesystem settings may cause this method to return true even though the entry is not executable by the effective owner/group.

static VALUE
rb_file_executable_p(VALUE obj, VALUE fname)
{
    return RBOOL(rb_eaccess(fname, X_OK) >= 0);
}

Like File.executable?, but checks against the real owner/group instead of the effective owner/group.

static VALUE
rb_file_executable_real_p(VALUE obj, VALUE fname)
{
    return RBOOL(rb_access(fname, X_OK) >= 0);
}

Return whether the specified object, a string path or IO object, exists:

# String paths.
File.exist?('README.md') # => true
File.exist?('.')         # => true
filepath = 't.tmp'
File.exist?(filepath)    # => false
File.write(filepath, 'foo')
File.exist?(filepath)    # => true
# File (IO object).
file = File.new(filepath)
File.exist?(file)        # => true
file.close               # Clean up.
File.unlink(filepath)    # Clean up.

Follows symbolic links:

# Symbolic links.
File.symlink('README.md', 'README.link')
File.symlink('nosuch', 'BROKEN.link')
File.exist?('README.link')  # => true
File.exist?('BROKEN.link')  # => false
File.unlink('README.link')  # Clean up.
File.unlink('BROKEN.link')  # Clean up.
static VALUE
rb_file_exist_p(VALUE obj, VALUE fname)
{
    struct stat st;

    if (rb_stat(fname, &st) < 0) return Qfalse;
    return Qtrue;
}

Returns the string absolute path for the given path.

Evaluates a relative path with respect to the directory given by dirpath:

Dir.chdir('/snap')
# Default dirpath.
File.expand_path('README')                  # => "/snap/README"
File.expand_path('bin')                     # => "/snap/bin"
File.expand_path('bin/../var')              # => "/snap/var"  # Cleaned.
# Other dirpath.
File.expand_path('../zip', '/usr/bin/ruby') # => "/usr/bin/zip"
Dir.chdir('/usr/bin')
File.expand_path('../../snap', __FILE__)    # => "/usr/snap"

Evaluates an absolute path without respect to dirpath:

File.expand_path('/snap')           # => "/snap"
File.expand_path('/snap', 'nosuch') # => "/snap"
File.expand_path('/snap/../snap')   # => "/snap"  # Cleaned.

More examples:

Dir.chdir('/usr/bin')
File.expand_path('../../snap', __FILE__) # => "/usr/snap"
File.expand_path('../../snap')           # => "/snap"
static VALUE
s_expand_path(int c, const VALUE * v, VALUE _)
{
    return rb_file_s_expand_path(c, v);
}

Returns the filename extension – usually the portion of the string path beginning from the last period:

File.extname('t.rb')         # => ".rb"
File.extname('foo.bar.t.rb') # => ".rb"
File.extname('foo/bar/t.rb') # => ".rb"
File.extname('nosuch.txt')   # => ".txt"  # Path need not exist.

Returns the entire string when there is no period:

Pathname('foo').extname # => ""

Returns an empty string when the only period is the first character:

File.extname('.irbrc') # => ""

Returns an empty string or '.' when path ends with a period:

File.extname('foo.') # => ""      # On Windows.
File.extname('foo.') # => "."     # Elsewhere.
File.extname('foo....') # => ""   # On Windows.
File.extname('foo....') # => "."  # Elsewhere.
static VALUE
rb_file_s_extname(VALUE klass, VALUE fname)
{
    const char *name;
    CheckPath(fname, name);
    rb_len_t len = RSTRING_LEN(fname);

    if (len < 1) {
        return rb_enc_str_new(0, 0, rb_str_enc_get(fname));
    }

    bool mb_enc = !rb_str_enc_fastpath(fname);
    rb_encoding *enc = rb_str_enc_get(fname);

    const char *ext = enc_find_extname(name, &len, mb_enc, enc);
    return rb_enc_str_new(ext, len, enc);
}

Returns whether the given object, a string path or IO object, represents a filesystem entry that exists and is a regular file; see File.ftype:

File.file?('/etc/passwd') # => true
File.file?('/etc')        # => false
File.file?($stdin)        # => false
File.file?('nosuch')      # => false
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));
}

Returns whether string pattern matches against string path, under the control of the given flags; see Filename Matching.

# File dir.rb, line 255
def fnmatch(pattern, path, flags = 0)
end
Also aliased as: fnmatch?
Alias for: fnmatch

Returns the string type of the object at path, one of:

  • 'file'.

  • 'directory'.

  • 'characterSpecial'.

  • 'blockSpecial'.

  • 'fifo'.

  • 'link'.

  • 'socket'.

Examples:

File.ftype('/etc/passwd') # => "file"
File.ftype('/etc')        # => "directory"
File.ftype("/dev/null")   # => "characterSpecial"
File.ftype("/dev/loop0")  # => "blockSpecial"

File.mkfifo('/tmp/pipe', 0o666)
File.ftype('/tmp/pipe')   # => "fifo"

File.symlink('/etc/passwd', '/tmp/link')
File.ftype('/tmp/link')   # => "link"

require 'socket'
UNIXServer.new('/tmp/socket')
File.ftype('/tmp/socket') # => "socket"

File.delete('/tmp/link', '/tmp/pipe', '/tmp/socket') # Clean up.

Returns 'unknown' if the type cannot be determined.

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.st_mode);
}

Returns false on Windows.

On other systems returns whether the effective group id of the calling process is the owner of the given object.

The given object may be the string path or an IO object:

filepath = '/tmp/t.tmp'
File.write(filepath, 'foo')
File.grpowned?(filepath)       # => true
File.grpowned?('/etc')         # => false
File.grpowned?('/etc/passwd')  # => false
File.grpowned?($stdin)         # => false
File.grpowned?('nosuch')       # => false
File.delete(filepath)          # Clean up.
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;
}

Returns whether the given objects represent filesystem entries that are identical; each object may be a string path or an IO object:

# Paths.
File.identical?('README.md', 'README.md')   # => true  # Same path.
File.identical?('README.md', './README.md') # => true  # Same entry.
File.identical?('.', '.')                   # => true  # Directory.
File.identical?('README.md', 'LEGAL')       # => false
File.identical?('README.md', 'nosuch')      # => false # Non-existent entry.
# Links and File object.
File.link('README.md', 'link')              # Symbolic link.
File.symlink('README.md', 'symlink')        # Hard link.
file = File.open('README.md', 'r')          # File object.
File.identical?('README.md', 'link')        # => true
File.identical?('README.md', 'symlink')     # => true
File.identical?('README.md', file)          # => true
# Clean up.
File.unlink('link')
File.unlink('symlink')
file.close
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
}

Returns a new string formed by joining the given string components with character '/':

File.join                   # => ""
File.join('foo')            # => "foo"
File.join(*%w[bar baz bat]) # => "bar/baz/bat"
static VALUE
rb_file_s_join(int argc, VALUE *argv, VALUE klass)
{
    return rb_file_join(argc, argv);
}

Not supported on Linux or Windows (raises NotImplementedError).

When supported: like File::chmod, but does not follow symbolic links, and therefore changes the mode of the entries given by paths; returns the number of paths given:

File.write('t.tmp', '')
File.symlink('t.tmp', 'link')
File.lstat('t.tmp').mode.to_s(8) # => "100664"
File.lstat('link').mode.to_s(8)  # => "120755"
File.lchmod(0777, 'link')
File.lstat('t.tmp').mode.to_s(8) # => "100664"
File.lstat('link').mode.to_s(8)  # => "120777"
File.delete('t.tmp')
File.delete('link')
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);
}

Not supported on some platforms (raises exception).

Calling process must have superuser privileges.

When supported: like File::chown, but does not follow symbolic links, and therefore changes the ownership of the entries given by paths; returns the number of paths given:

# Super user; all privileges.
Process.uid # => 0
Process.gid # => 0
# Create regular file and symbolic link to it.
File.write('t.tmp', '')
File.symlink('t.tmp', 'link')
Capture original statuses.
fstat0 = File.stat('t.tmp')  # Method ::stat; status of file.
lstat0 = File.lstat('link')  # Method ::lstat; status of link.
# Original user ids and group ids.
fstat0.uid => 0
fstat0.gid => 0
lstat0.uid => 0
lstat0.gid => 0
# Change ids for link.
File.lchown(1000, 1000, 'link') # => 1
# Capture new statuses.
fstat1 = File.stat('t.tmp')
lstat1 = File.stat('link')
# User id and group id for file not changed..
fstat1.uid # => 0
fstat1.gid # => 0
# User is and group id for link changed.
lstat1.uid # => 1000
lstat1.gid # => 1000
Clean up.
File.delete('t.tmp')
File.delete('link')
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);
}

Returns a new File::Stat object for the entry at path. Unline File.stat, does not follow symbolic links; therefore the returned object contains information for the entry at path, regardless of whether is a symbolic link:

filepath = '/etc/passwd'
linkpath = '/tmp/foo'
File.symlink(filepath, linkpath)
# Method File.lstat does not follow the symlink, so the birthtimes are different.
File.lstat(filepath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
File.lstat(linkpath).birthtime # => 2026-09-23 14:01:18.248754979 -0500
# Method File.stat follows the symlink, so the birthtimes are the same.
File.stat(filepath).birthtime  # => 2025-06-10 11:10:47.358999941 -0500
File.stat(linkpath).birthtime  # => 2025-06-10 11:10:47.358999941 -0500
File.delete(linkpath)          # Clean up.
static VALUE
rb_file_s_lstat(VALUE klass, VALUE fname)
{
#ifdef HAVE_LSTAT
    rb_io_stat_data st;

    FilePathValue(fname);
    fname = rb_str_encode_ospath(fname);
    if (lstatx_without_gvl(StringValueCStr(fname), &st, STATX_ALL) == -1) {
        rb_sys_fail_path(fname);
    }
    return rb_statx_new(&st);
#else
    return rb_file_s_stat(klass, fname);
#endif
}

Like File::utime, but does not follow symbolic links, and therefore changes the times of the entries given by paths, regardless of whether they are symbolic links; returns the number of paths given:

# Create a file and a link to it.
file_path = 't.tmp'
File.write(file_path, '')
link_path = 'link'
File.symlink(file_path, link_path)
# Take snapshots of both.
file_stat = File.stat(file_path)
link_stat = File.lstat(link_path)
# Fetch access times and modification times of both.
file_stat.atime # => 2026-06-15 10:45:11.376753268 -0500
file_stat.mtime # => 2026-06-15 10:44:47.335854904 -0500
link_stat.atime # => 2026-06-15 10:44:59.788801128 -0500
link_stat.mtime # => 2026-06-15 10:44:49.367845961 -0500
# Update access time and modification time of the link.
time = Time.now # => 2026-06-15 10:48:57.847422496 -0500
File.lutime(time, time, link_path)
# Take fresh snapshots of both.
file_stat = File.stat(file_path)
link_stat = File.lstat(link_path)
# Fetch access time and modification time of file (not changed).
file_stat.atime # => 2026-06-15 10:45:11.376753268 -0500
file_stat.mtime # => 2026-06-15 10:44:47.335854904 -0500
# Fetch access time and modification time of link (changed).
link_stat.atime # => 2026-06-15 10:49:27.119146136 -0500
link_stat.mtime # => 2026-06-15 10:48:57.847422496 -0500
# Clean up.
File.delete(file_path)
File.delete(link_path)

Arguments atime and mtime may be Time objects (as above).

Either or both may be integers; when an integer i is passed, Time.new(i) is used.

Either or both may be nil, in which case Time.now is used.

See File System Timestamps.

static VALUE
rb_file_s_lutime(int argc, VALUE *argv, VALUE _)
{
    return utime_internal_i(argc, argv, TRUE);
}

Creates a FIFO special file at the given path, with the permissions given by mode; see Filesystem Modes:

path = '/tmp/pipe'
File.mkfifo(path)
File.pipe?(path) # => true
File.ftype(path) # => "fifo"
File.unlink(path)

Not implemented on Windows.

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 (IO_WITHOUT_GVL(nogvl_mkfifo, &ma)) {
        rb_sys_fail_path(path);
    }
    return INT2FIX(0);
}

Returns a new Time object containing the modification time for the given object, which may be a string path or an IO object; see Modification Time:

# Create directory; directory mtime established.
dirpath = 'doc/foo'                    # => "doc/foo"
Dir.mkdir(dirpath)
File.mtime(dirpath)                    # => 2026-09-19 09:01:30.045928322 -0500
# Create file therein; file mtime established, directory mtime updated.
filepath = File.join(dirpath, 't.tmp') # => "doc/foo/t.tmp"
File.write(filepath, 'foo')
File.mtime(filepath)                   # => 2026-09-19 09:02:32.860803131 -0500
File.mtime(dirpath)                    # => 2026-09-19 09:02:32.860803131 -0500
# Modify file; file mtime updated, directory mtime unchanged.
File.write(filepath, 'bar')
File.mtime(filepath)                   # => 2026-09-19 09:03:29.875611413 -0500
File.mtime(dirpath)                    # => 2026-09-19 09:02:32.860803131 -0500
FileUtils.rm_rf(dirpath)               # Clean up.
File.mtime($stdout)                    # => 2026-09-19 09:27:52 -0500
$stdout.flush
File.mtime($stdout)                    # => 2026-09-19 09:28:08 -0500
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_time(stat_mtimespec(&st));
}

Opens the file as specified by the given arguments. Creates and returns a new open File object for that file; the opened file is in non-synchronous mode.

Argument path must the string path to an existing filesystem entry:

file = File.new('doc/maintainers.md') # => #<File:doc/maintainers.md>
file.close                            # Clean up.
tty = File.new('/dev/tty')            # => #<File:/dev/tty>
tty.close                             # Clean up.

Note that the caller is responsible for closing the file; see File.open for automatic closing.

Optional argument mode (defaults to 'r') must specify a valid mode; see Access Modes:

file = File.new('t.tmp', 'w')          # => #<File:t.tmp>
file.close                             # Clean up.
file = File.new('t.tmp', File::RDONLY) # => #<File:t.tmp>
file.close                             # Clean up.

Optional argument permissions (defaults to 0666) must specify valid permissions; see File Permissions:

file = File.new('t.tmp', 'w', 0644)    # => #<File:t.tmp>
file.close                             # Clean up.
file = File.new('t.tmp', 'w', 0444)    # => #<File:t.tmp>
file.close                             # Clean up.

Optional keyword arguments options specify:

static VALUE
rb_file_initialize(int argc, VALUE *argv, VALUE io)
{
    if (RFILE(io)->fptr) {
        rb_raise(rb_eRuntimeError, "reinitializing File");
    }
    VALUE fname, vmode, vperm, opt;
    int posargc = rb_scan_args(argc, argv, "12:", &fname, &vmode, &vperm, &opt);
    if (posargc < 3) {          /* perm is File only */
        VALUE fd = rb_check_to_int(fname);

        if (!NIL_P(fd)) {
            return io_initialize(io, fd, vmode, opt);
        }
    }
    return rb_open_file(io, fname, vmode, vperm, opt);
}

Creates a new File object via File.new with the given arguments.

With no block given, returns the File object.

With a block given, calls the block with the File object, closes the File object, and returns the block’s value:

File.open('doc/maintainers.md') {|file| file.size } # => 14900

Note that the File object is automatically closed even if the block raises an exception.

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;
}

Returns whether the given object represents a filesystem entry or IO object that exists and is owned by the user of the current process:

filepath = 'doc/t.tmp'
File.write(filepath, 'foo')
File.owned?(filepath) # => true
File.delete(filepath) # Clean up.
dirpath = 'doc/tmp'
Dir.mkdir(dirpath)
File.owned?(dirpath)  # => true
Dir.rmdir(dirpath)    # Clean up.
File.owned?($stdin)   # => true
File.owned?('/etc')   # => false
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());
}

Returns a string representation of the given path:

File.path(File::NULL) # => "/dev/null"
File.path('/tmp')     # => "/tmp"
File.path('../ruby')  # => "../ruby"
File.path($stdin)     # => "<STDIN>"
File.path('nosuch')   # => "nosuch"
static VALUE
rb_file_s_path(VALUE klass, VALUE fname)
{
    return rb_get_path(fname);
}

Returns whether the entry at the given path is a pipe:

File.pipe?('doc/syntax/')        # => false  # Directory.
File.pipe?('doc/maintainers.md') # => false  # Regular file.
File.pipe?('nosuch')             # => false  # Non-existent.
path = '/tmp/foo'
File.mkfifo(path)
File.pipe?(path)                 # => true
File.delete(path)                # Clean up.
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;
}

Returns whether the entry at the given path exists and is readable by the owner and group of the current process; see Permissions:

path = '/tmp/secret.txt'
File.write(path, 'foo')
File.readable?(path)     # => true
File.chmod(0o000, path)
File.readable?(path)     # => false
File.delete(path)        # Clean up.
File.readable?('nosuch') # => false
static VALUE
rb_file_readable_p(VALUE obj, VALUE fname)
{
    return RBOOL(rb_eaccess(fname, R_OK) >= 0);
}

Like File.readable?, but checks against the real user and group ids instead of the effective ids.

static VALUE
rb_file_readable_real_p(VALUE obj, VALUE fname)
{
    return RBOOL(rb_access(fname, R_OK) >= 0);
}

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.

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);
}

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.

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);
}

Moves the entry at the given path to the given new_path.

Does not follow symbolic links; if the entry is a symlink, the link itself is renamed.

The examples below use two temporary directories:

src_dirpath = '/tmp/src/' # => "/tmp/src/"
dst_dirpath = '/tmp/dst/' # => "/tmp/dst/"
Dir.mkdir(src_dirpath)
Dir.mkdir(dst_dirpath)

The entry to be renamed may be a file:

src_filepath = File.join(src_dirpath, 't.tmp') # => "/tmp/src/t.tmp"
File.write(src_filepath, 'foo')
dst_filepath = File.join(dst_dirpath, 'u.tmp') # => "/tmp/dst/u.tmp"
File.rename(src_filepath, dst_filepath)
File.exist?(src_filepath)                      # => false
File.exist?(dst_filepath)                      # => true
File.delete(dst_filepath)                      # Clean up.

The entry to be renamed may be a symbolic link:

filepath = File.join(src_dirpath, 't.tmp') # => "/tmp/src/t.tmp"
File.write(src_filepath, 'foo')
linkpath = File.join(src_dirpath, 'u.tmp') # => "/tmp/src/u.tmp"
File.symlink(filepath, linkpath)
File.readlink(linkpath)                    # => "/tmp/src/t.tmp"
newpath = File.join(dst_dirpath, 'v.tmp')  # => "/tmp/dst/v.tmp"
File.rename(linkpath, newpath)             # Symlink not followed.
File.readlink(newpath)                     # => "/tmp/src/t.tmp"
File.delete(filepath, newpath)             # Clean up.

The entry to be renamed may be a directory:

old_dirpath = File.join(src_dirpath, 'olddir') # => "/tmp/src/olddir"
Dir.mkdir(old_dirpath)
new_dirpath = File.join(dst_dirpath, 'newdir') # => "/tmp/dst/newdir"
File.rename(old_dirpath, new_dirpath)
File.directory?(new_dirpath)                   # => true
Dir.rmdir(new_dirpath)                         # Clean up.

Clean up:

FileUtils.rm_rf(src_dirpath) # => ["/tmp/src/"]
FileUtils.rm_rf(dst_dirpath)  # => ["/tmp/dst/"]

Raises SystemCallError if the file cannot be renamed.

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 (IO_WITHOUT_GVL_INT(no_gvl_rename, &ra) < 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);
}

Returns whether the setgid bit is set in the special bits for the given object, which may be a path or an IO object:

path = '/tmp/t.tmp'
File.write(path, 'foo')
mode = File.stat(path).mode.to_s(8) # => "100664"
File.setgid?(path)                  # => false
File.chmod(0o2644, path)            # Set the bit.
mode = File.stat(path).mode.to_s(8) # => "102644"
File.setgid?(path)                  # => true
File.delete(path)                   # Clean up.
File.setgid?($stdin)                # => false

On Windows, the bit is never set; the method always returns false.

static VALUE
rb_file_sgid_p(VALUE obj, VALUE fname)
{
#ifdef S_ISGID
    return check3rdbyte(fname, S_ISGID);
#else
    return Qfalse;
#endif
}

Returns whether the setuid bit is set in the special bits for the given object, which may be a path or an IO object:

path = '/tmp/t.tmp'
File.write(path, 'foo')
mode = File.stat(path).mode.to_s(8) # => "100664"
File.setuid?(path)                  # => false
File.chmod(0o4644, path)            # Set the bit.
mode = File.stat(path).mode.to_s(8) # => "104644"
File.setuid?(path)                  # => true
File.delete(path)                   # Clean up.
File.setuid?($stdin)                # => false

On Windows, the bit is never set; the method always returns false.

static VALUE
rb_file_suid_p(VALUE obj, VALUE fname)
{
#ifdef S_ISUID
    return check3rdbyte(fname, S_ISUID);
#else
    return Qfalse;
#endif
}

Returns the size in bytes of the given object, which may be a path or an IO object:

File.size('doc/maintainers.md') # => 14900  # Regular file.
File.size('doc/syntax/')        # => 4096   # Directory.
File.size($stdin)               # => 0      # IO object.
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);
}

Returns the size in bytes of the given object if the entry exists and has non-zero size, nil otherwise; the object may be a path or an IO object:

# Regular file.
path = '/tmp/t.tmp'
File.write(path, 'foo')
File.size?(path)   # => 3    # Non-zero size.
File.write(path, '')
File.size?(path)   # => nil  # Zero size.
File.delete(path)            # Clean up.
File.size?(path)   # => nil  # Non-existent.
# Directory.
path = '/tmp/foo/'
Dir.mkdir(path)
File.size?(path)   # => 4096 # Non-zero size.
Dir.rmdir(path)              # Clean up.
File.size?(path)   # => nil  # Non-existent.
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);
}

Returns whether the given object represents a socket; the object may be a path or an IO object:

require 'socket'
sock_path = '/tmp/socket'
server = UNIXServer.new(sock_path)
File.socket?(sock_path) # => true
File.delete(sock_path)  # Clean up.
file_path = '/etc/passwd'
File.file?(file_path)   # => true
File.socket?(file_path) # => false
File.socket?($stdin)    # => false
File.socket?('nosuch')  # => false
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;
}

Returns a 2-element array of strings containing the ::dirname and ::basename of the the given string:

File.split('doc/maintainers.md') # => ["doc", "maintainers.md"]
File.split('doc/')               # => [".", "doc"]
File.split('README.md')          # => [".", "README.md"]
File.split('/tmp/nosuch')        # => ["/tmp", "nosuch"]
File.split('@@##$$/%%^^&&')      # => ["@@#\#$$", "%%^^&&"]
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));
}

Returns a new File::Stat object for the entry at path. Unlike File.lstat, does follow symbolic links; therefore if the entry is a symbolic link, the returned object contains information for the target entry, not the symbolic link:

filepath = '/etc/passwd'
linkpath = '/tmp/foo'
File.symlink(filepath, linkpath)
# Method File.stat follows the symlink, so the birthtimes are the same.
File.stat(filepath).birthtime  # => 2025-06-10 11:10:47.358999941 -0500
File.stat(linkpath).birthtime  # => 2025-06-10 11:10:47.358999941 -0500
# Method File.lstat does not follow the symlink, so the birthtimes are different.
File.lstat(filepath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
File.lstat(linkpath).birthtime # => 2026-09-23 14:01:18.248754979 -0500
File.delete(linkpath)          # Clean up.
static VALUE
rb_file_s_stat(VALUE klass, VALUE fname)
{
    rb_io_stat_data st;

    FilePathValue(fname);
    fname = rb_str_encode_ospath(fname);
    if (statx_without_gvl(RSTRING_PTR(fname), &st, STATX_ALL) < 0) {
        rb_sys_fail_path(fname);
    }
    return rb_statx_new(&st);
}

Returns whether the sticky bit is set in the special bits for the given object, which may be a path or an IO object:

filepath = '/tmp/t.tmp'
File.write(filepath, 'foo')
mode = File.stat(filepath).mode.to_s(8) # => "100664"
File.sticky?(filepath)                  # => false
File.chmod(01644, filepath)             # Set sticky bit.
mode = File.stat(filepath).mode.to_s(8) # => "101644"
File.sticky?(filepath)                  # => true
File.delete(filepath)                   # Clean up.
File.sticky?($stdin)                    # => false
File.sticky?('nosuch')                  # => false

Returns false on Windows.

static VALUE
rb_file_sticky_p(VALUE obj, VALUE fname)
{
#ifdef S_ISVTX
    return check3rdbyte(fname, S_ISVTX);
#else
    return Qfalse;
#endif
}

Adjusts the size of file filepath to the given size:

filepath = '/tmp/t.tmp'
File.write(filepath, '0123456789')
File.read(filepath)   # => "0123456789"
File.truncate(filepath, 5)
File.read(filepath)   # => "01234"

Pads with null characters if necessary:

File.truncate(filepath, 10)
File.read(filepath)   # => "01234\u0000\u0000\u0000\u0000\u0000"
File.delete(filepath) # Clean up.
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 = IO_WITHOUT_GVL_INT(nogvl_truncate, &ta);
    if (r < 0)
        rb_sys_fail_path(path);
    return INT2FIX(0);
}

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
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);
}

For the entry at the paths in paths, updates its access time to the given atime and its modification time to the given mtime; see Filesystem Timestamps. Returns the number of entries updated. Each path points to a file or directory.

Each given time may be a Time object, an integer representing a time, or nil (meaning Time.now):

filepath = '/tmp/t.tmp'
File.write(filepath, 'foo')
File.atime(filepath)  # => 2026-09-29 12:38:29.889703781 -0500
File.mtime(filepath)  # => 2026-09-29 12:38:29.889703781 -0500
time = Time.now
File.utime(time, time, filepath)
File.atime(filepath)  # => 2026-09-29 12:38:52.533160634 -0500
File.mtime(filepath)  # => 2026-09-29 12:38:52.533160634 -0500
File.utime(0, 0, filepath)
File.atime(filepath)  # => 1969-12-31 18:00:00 -0600
File.mtime(filepath)  # => 1969-12-31 18:00:00 -0600
File.utime(nil, nil, filepath)
File.atime(filepath)  # => 2026-09-29 12:39:50.859421265 -0500
File.mtime(filepath)  # => 2026-09-29 12:39:50.859421265 -0500
File.delete(filepath) # Clean up.

Raises an exception if any entry cannot be updated; some entries may have already been updated.

Follows symbolic links; use File.lutime to update the times for symbolic links.

static VALUE
rb_file_s_utime(int argc, VALUE *argv, VALUE _)
{
    return utime_internal_i(argc, argv, FALSE);
}

If the the given object exists and is readable by others, returns the integer permissions for the entry; otherwise, returns nil:

filepath = '/tmp/t.tmp'
File.world_readable?(filepath)         # => nil   # Non-existent.
File.write(filepath, 'foo')                       # Create file.
File.world_readable?(filepath).to_s(8) # => "664" # World-readable.
File.chmod(0o000, filepath)                       # Change to unreadable.
File.world_readable?(filepath)         # => nil   # Not world-readable.
File.delete(filepath)                             # Clean up.
File.world_readable?('.').to_s(8)      # => "775" # Directory.
File.world_readable?($stdin)           # => nil   # IO object.
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;
}

If the given object exists and is writable by others, returns the integer permissions for the entry; otherwise, returns nil:

filepath = '/tmp/t.tmp'
File.world_writable?(filepath)         # => nil    # Non-existent.
File.write(filepath, 'foo')                        # Create file.
File.world_writable?(filepath)         # => nil    # Not world-writable.
File.chmod(0o777, filepath)                        # Make world-writable.
File.world_writable?(filepath).to_s(8) # => "777"  # World-writable.
File.delete(filepath)                              # Clean up.
File.world_writable?('/tmp').to_s(8)   # => "777"  # Directory.
File.world_writable?($stdin)           # => nil    # IO object.
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;
}

Returns whether given object exists and is writable by the owner and group in the current process:

filepath = '/tmp/secret.txt'
File.writable?(filepath)   # => false  # Non-existent.
File.write(filepath, 'foo')            # Create file.
File.writable?(filepath)   # => true   # Writable.
File.chmod(0o000, filepath)            # Make non-writable.
File.writable?(filepath)   # => false  # Not writable.
File.delete(filepath)                  # Clean up.
File.writable?('/etc')     # => false  # Directory.
File.writable?($stdin)     # => false  # IO object.

Note that filesystem security features may cause this method to return true even when the file is not writable by the owner and group.

static VALUE
rb_file_writable_p(VALUE obj, VALUE fname)
{
    return RBOOL(rb_eaccess(fname, W_OK) >= 0);
}

Like File.writable?, but checks against the real owner and group instead of the effective owner and group.

Note that filesystem security features may cause this method to return true even when the object is not writable by the real owner and group.

static VALUE
rb_file_writable_real_p(VALUE obj, VALUE fname)
{
    return RBOOL(rb_access(fname, W_OK) >= 0);
}

Returns whether the given object exists and has size zero.

The given object may be the path to a file:

filepath = '/tmp/t.tmp'
File.write(filepath, 'foo') # File has non-zero size.
File.zero?(filepath)        # => false
File.truncate(filepath, 0)  # File has zero size.
File.zero?(filepath)        # => true
File.delete(filepath)       # Clean up.

The given object may be the path to a directory:

dirpath = '/tmp/foo'
Dir.mkdir(dirpath)
Dir.new(dirpath).children.size # => 0
# Size is filesystem-dependent; may or may not be zero.
File.size(dirpath)             # => 4096
File.zero?(dirpath)            # => false
filepath = '/tmp/foo/t.tmp'    # => "/tmp/foo/t.tmp"
File.write(filepath, 'foo')    # Add a child.
Dir.new(dirpath).children.size # => 1
File.size(dirpath)             # => 4096
File.zero?(dirpath)            # => false
FileUtils.rm_rf(dirpath)       # Clean up.

The given object may be an IO object:

File.zero?($stdin) # => true

The given object may be none of the above:

File.zero?('nosuch') # => false
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);
}

Public Instance Methods

Returns a new Time object containing the time of the most recent access to self. See File System Timestamps.

Access time for a file is established when it is created, and may be updated when the file content is read:

filepath = '/tmp/t.tmp'
File.exist?(filepath)       # => false
File.write(filepath, 'foo') # Establishes access time.
file = File.new(filepath)
file.atime                  # => 2026-10-04 14:48:30.323100327 -0500
file.read                   # Updates access time.
file.atime                  # => 2026-10-04 14:49:01.104340829 -0500
# Clean up.
file.close
File.delete(filepath)
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_time(stat_atimespec(&st));
}

Returns a new Time object containing the create time for self:

filepath = 't.tmp'
File.write(filepath, 'foo')
file = File.new(filepath)
file.birthtime # => 2026-04-14 15:53:45.002656 -0500
File.write(filepath, 'bar')
file.birthtime # => 2026-04-14 15:53:45.002656 -0500
file.close
File.delete(filepath)
file.birthtime # Raises IOError: closed stream

See File System Timestamps.

static VALUE
rb_file_birthtime(VALUE obj)
{
    rb_io_t *fptr;
    rb_io_stat_data st;

    GetOpenFile(obj, fptr);
    if (fstatx_without_gvl(fptr, &st, STATX_BTIME) == -1) {
        rb_sys_fail_path(fptr->pathv);
    }
    return statx_birthtime(&st);
}

Changes the mode of self; returns ‘0’. See Filesystem Modes and especially Filesystem Modes.

filepath = '/tmp/t.tmp'
File.write(filepath, 'foo')
'%06o' % File.stat(filepath).mode      # => "100664"
file = File.new(filepath)
file.chmod(0o755)
'%06o' % File.stat(filepath).mode      # => "100755"
# Clean up.
file.close
File.delete(filepath)
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 (rb_fchmod(fptr, 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 (rb_chmod(RSTRING_PTR(path), mode) == -1)
        rb_sys_fail_path(fptr->pathv);
#endif

    return INT2FIX(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)
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 (rb_chown(RSTRING_PTR(path), o, g) == -1)
        rb_sys_fail_path(fptr->pathv);
#else
    if (rb_fchown(fptr->fd, o, g) == -1)
        rb_sys_fail_path(fptr->pathv);
#endif

    return INT2FIX(0);
}

On Windows, returns the birthtime for the entry in self.

On other systems, returns a new Time object containing the time of the most recent metadata change to the entry in self; see File System Timestamps:

# A directory.
dirpath = '/tmp/dir'
Dir.mkdir(dirpath)                     # Establishes directory ctime.
dir = File.new(dirpath) # (Dir does not have method ctime; we use File.)
dir.ctime                              # => 2026-10-05 17:23:49.406452569 -0500
# A file therein.
filepath = File.join(dirpath, 't.tmp') # => "/tmp/dir/t.tmp"
File.write(filepath, 'foo')            # Establishes file ctime.
file = File.new(filepath)
file.ctime                             # => 2026-10-05 17:26:26.467758515 -0500
dir.ctime                              # => 2026-10-05 17:26:26.467758515 -0500
File.write(filepath, 'bar')            # Updates file ctime; not directory ctime.
file.ctime                             # => 2026-10-05 17:28:26.307497599 -0500
dir.ctime                              # => 2026-10-05 17:26:26.467758515 -0500
FileUtils.rm_rf(dirpath)               # Clean up.
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_time(stat_ctimespec(&st));
}

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
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_io_blocking_region(fptr, rb_thread_flock, op) < 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);
}

Returns a new File::Stat object for self. Unlike File#stat, does not follow symbolic links; therefore if self is a symbolic link, the returned object contains information for self, not the target entry:

file_path = '/etc/passwd'
link_path = '/tmp/foo'
File.symlink(file_path, link_path)
file = File.new(file_path) # => #<File:/etc/passwd>
link = File.new(link_path) # => #<File:/tmp/foo>
# Method lstat does not follow the symlink, so the birthtimes are different.
file.lstat.birthtime       # => 2025-06-10 11:10:47.358999941 -0500
link.lstat.birthtime       # => 2026-09-23 16:35:59.321566598 -0500
# Method stat does follow the symlink, so the birthtimes are the same.
file.stat.birthtime        # => 2025-06-10 11:10:47.358999941 -0500
link.stat.birthtime        # => 2025-06-10 11:10:47.358999941 -0500
File.delete(link_path)     # Clean up.
static VALUE
rb_file_lstat(VALUE obj)
{
#ifdef HAVE_LSTAT
    rb_io_t *fptr;
    rb_io_stat_data st;
    VALUE path;

    GetOpenFile(obj, fptr);
    if (NIL_P(fptr->pathv)) return Qnil;
    path = rb_str_encode_ospath(fptr->pathv);
    if (lstatx_without_gvl(RSTRING_PTR(path), &st, STATX_ALL) == -1) {
        rb_sys_fail_path(fptr->pathv);
    }
    return rb_statx_new(&st);
#else
    return rb_io_stat(obj);
#endif
}

Returns a new Time object containing the modification time for self; see Modification Time:

path = 't.tmp'
file = File.new(path, 'w+')
file.mtime # => 2026-09-19 08:41:29.357110007 -0500
file.write('foo')
file.flush
file.mtime # => 2026-09-19 08:41:46.321965574 -0500
File.unlink(path)
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_time(stat_mtimespec(&st));
}

Returns the size of self in bytes:

File.new('doc/maintainers.md').size # => 14900  # Regular file.
File.new('doc/syntax/').size        # => 4096   # Directory.
static VALUE
file_size(VALUE self)
{
    return OFFT2NUM(rb_file_size(self));
}

Adjusts the size of self to the given size, regardless of the current position; does not adjust the position:

filepath = '/tmp/t.tmp'
file = File.new(filepath, 'w+')
file.write('0123456789')
file.truncate(5)
file.pos  # => 10
file.rewind
file.read # => "01234"

Pads with null characters if necessary:

file.truncate(10)
file.pos  # => 5
file.rewind
file.read # => "01234\u0000\u0000\u0000\u0000\u0000"
# Clean up.
file.close
File.delete(filepath)
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_io_blocking_region(fptr, nogvl_ftruncate, &fa) < 0) {
        rb_sys_fail_path(fptr->pathv);
    }
    return INT2FIX(0);
}