class File - RDoc Documentation (original) (raw)

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:

text = <<~EOT First line Second line

Fourth line Fifth line EOT

russian = "\u{442 435 441 442}"

data = "\u9990\u9991\u9992\u9993\u9994"

File.write('t.txt', text)

File.write('t.rus', russian)

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:

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:

Read/Write Modes for Existing File
Read/Write Modes for File To Be Created

Note that modes 'r' and 'r+' are not allowed for a non-existent file (exception raised).

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:

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')
File.new('t.dat', 'rxb')

File-Create Mode

The following may be suffixed to any writable string mode above:

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')
File.new('t.dat', 'rxb')

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

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:

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 f.internal_encoding f = File.new('t.dat', 'rb:UTF-16') f.external_encoding f.internal_encoding f = File.new('t.dat', 'rb:UTF-16:UTF-16') f.external_encoding f.internal_encoding f.close

The numerous encoding names are available in array Encoding.name_list:

Encoding.name_list.take(3)

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)

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:

Here, class File provides methods that are useful for:

Creating

Querying

Paths

Times

Types

Contents

Settings

Other

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

absolute_path(file_name [, dir_string] ) → abs_file_name click to toggle source

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")

static VALUE s_absolute_path(int c, const VALUE * v, VALUE _) { return rb_file_s_absolute_path(c, v); }

absolute_path?(file_name) → true or false click to toggle source

Returns true if file_name is an absolute path, and false otherwise.

File.absolute_path?("c:/foo")

static VALUE s_absolute_path_p(VALUE klass, VALUE fname) { VALUE path = rb_get_path(fname);

if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse;
return Qtrue;

}

atime(file_name) → time click to toggle source

Returns the last access time for the named file as a Time object.

file_name can be an IO object.

File.atime("testfile")

static VALUE rb_file_s_atime(VALUE klass, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) {
    int e = errno;
    FilePathValue(fname);
    rb_syserr_fail_path(e, fname);
}
return stat_atime(&st);

}

basename(file_name [, suffix] ) → base_name click to toggle source

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")
File.basename("/home/gumby/work/ruby.rb", ".rb")
File.basename("/home/gumby/work/ruby.rb", ".*")

static VALUE rb_file_s_basename(int argc, VALUE *argv, VALUE _) { VALUE fname, fext, basename; const char *name, *p; long f, n; rb_encoding *enc;

fext = Qnil;
if (rb_check_arity(argc, 1, 2) == 2) {
    fext = argv[1];
    StringValue(fext);
    enc = check_path_encoding(fext);
}
fname = argv[0];
FilePathStringValue(fname);
if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
    enc = rb_enc_get(fname);
    fext = Qnil;
}
if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname)))
    return rb_str_new_shared(fname);

p = ruby_enc_find_basename(name, &f, &n, enc);
if (n >= 0) {
    if (NIL_P(fext)) {
        f = n;
    }
    else {
        const char *fp;
        fp = StringValueCStr(fext);
        if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
            f = n;
        }
        RB_GC_GUARD(fext);
    }
    if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
}

basename = rb_str_new(p, f);
rb_enc_copy(basename, fname);
return basename;

}

birthtime(file_name) → time click to toggle source

Returns the birth time for the named file.

file_name can be an IO object.

File.birthtime("testfile")

If the platform doesn’t have birthtime, raises NotImplementedError.

VALUE rb_file_s_birthtime(VALUE klass, VALUE fname) { statx_data st;

if (rb_statx(fname, &st, STATX_BTIME) < 0) {
    int e = errno;
    FilePathValue(fname);
    rb_syserr_fail_path(e, fname);
}
return statx_birthtime(&st, fname);

}

blockdev?(filepath) → true or false click to toggle source

Returns true if filepath points to a block device, false otherwise:

File.blockdev?('/dev/sda1')
File.blockdev?(File.new('t.tmp'))

static VALUE rb_file_blockdev_p(VALUE obj, VALUE fname) { #ifndef S_ISBLK

ifdef S_IFBLK

define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)

else

define S_ISBLK(m) (0) /* anytime false */

endif

#endif

#ifdef S_ISBLK struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
if (S_ISBLK(st.st_mode)) return Qtrue;

#endif return Qfalse; }

chardev?(filepath) → true or false click to toggle source

Returns true if filepath points to a character device, false otherwise.

File.chardev?($stdin)
File.chardev?('t.txt')

static VALUE rb_file_chardev_p(VALUE obj, VALUE fname) { #ifndef S_ISCHR

define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)

#endif

struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
if (S_ISCHR(st.st_mode)) return Qtrue;

return Qfalse;

}

chmod(mode_int, file_name, ... ) → integer click to toggle source

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")

static VALUE rb_file_s_chmod(int argc, VALUE *argv, VALUE _) { mode_t mode;

apply2args(1);
mode = NUM2MODET(*argv++);

return apply2files(chmod_internal, argc, argv, &mode);

}

chown(owner_int, group_int, file_name, ...) → integer click to toggle source

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")

static VALUE rb_file_s_chown(int argc, VALUE *argv, VALUE _) { struct chown_args arg;

apply2args(2);
arg.owner = to_uid(*argv++);
arg.group = to_gid(*argv++);

return apply2files(chown_internal, argc, argv, &arg);

}

ctime(file_name) → time click to toggle source

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")

static VALUE rb_file_s_ctime(VALUE klass, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) {
    int e = errno;
    FilePathValue(fname);
    rb_syserr_fail_path(e, fname);
}
return stat_ctime(&st);

}

delete(file_name, ...) → integer click to toggle source

unlink(file_name, ...) → integer

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. Since the underlying implementation relies on the unlink(2) system call, the type of exception raised depends on its error type (see linux.die.net/man/2/unlink) and has the form of e.g. Errno::ENOENT.

See also Dir::rmdir.

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

directory?(path) → true or false click to toggle source

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?('.')
File.directory?('foo')
File.symlink('.', 'dirlink')
File.directory?('dirlink')
File.symlink('t,txt', 'filelink') File.directory?('filelink')

Argument path can be an IO object.

VALUE rb_file_directory_p(VALUE obj, VALUE fname) { #ifndef S_ISDIR

define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)

#endif

struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
if (S_ISDIR(st.st_mode)) return Qtrue;
return Qfalse;

}

dirname(file_name, level = 1) → dir_name click to toggle source

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")

If level is given, removes the last level components, not only one.

File.dirname("/home/gumby/work/ruby.rb", 2) File.dirname("/home/gumby/work/ruby.rb", 4)

static VALUE rb_file_s_dirname(int argc, VALUE *argv, VALUE klass) { int n = 1; if ((argc = rb_check_arity(argc, 1, 2)) > 1) { n = NUM2INT(argv[1]); } return rb_file_dirname_n(argv[0], n); }

zero?(file_name) → true or false click to toggle source

Returns true if the named file exists and has a zero size.

file_name can be an IO object.

static VALUE rb_file_zero_p(VALUE obj, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
return RBOOL(st.st_size == 0);

}

executable?(file_name) → true or false click to toggle source

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.

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

executable_real?(file_name) → true or false click to toggle source

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.

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

exist?(file_name) → true or false click to toggle source

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.

static VALUE rb_file_exist_p(VALUE obj, VALUE fname) { struct stat st;

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

}

expand_path(file_name [, dir_string] ) → abs_file_name click to toggle source

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~_user_” expands to the named user’s home directory.

File.expand_path("~oracle/bin")

A simple example of using dir_string is as follows.

File.expand_path("ruby", "/usr/bin")

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)

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.

static VALUE s_expand_path(int c, const VALUE * v, VALUE _) { return rb_file_s_expand_path(c, v); }

extname(path) → string click to toggle source

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")
File.extname("a/b/d/test.rb")
File.extname(".a/b/d/test.rb")
File.extname("foo.")
File.extname("foo.")
File.extname("test")
File.extname(".profile")
File.extname(".profile.sh")

static VALUE rb_file_s_extname(VALUE klass, VALUE fname) { const char *name, *e; long len; VALUE extname;

FilePathStringValue(fname);
name = StringValueCStr(fname);
len = RSTRING_LEN(fname);
e = ruby_enc_find_extname(name, &len, rb_enc_get(fname));
if (len < 1)
    return rb_str_new(0, 0);
extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */
return extname;

}

file?(file) → true or false click to toggle source

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.

static VALUE rb_file_file_p(VALUE obj, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
return RBOOL(S_ISREG(st.st_mode));

}

fnmatch( pattern, path, [flags] ) → (true or false) click to toggle source

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:

*

Matches any file. Can be restricted by other values in the glob. Equivalent to /.*/x in regexp.

*

Matches all regular files

c*

Matches all files beginning with c

*c

Matches all files ending with c

*c*

Matches all files that have c in them (including at the beginning or end).

To match hidden files (that start with a .) 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 ([^a-z]).

\

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')
File.fnmatch('cat', 'category')

File.fnmatch('c{at,ub}s', 'cats')
File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB)

File.fnmatch('c?t', 'cat')
File.fnmatch('c??t', 'cat')
File.fnmatch('c*', 'cats')
File.fnmatch('c*t', 'c/a/b/t')
File.fnmatch('ca[a-z]', 'cat')
File.fnmatch('ca[^t]', 'cat')

File.fnmatch('cat', 'CAT')
File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) File.fnmatch('cat', 'CAT', File::FNM_SYSCASE)

File.fnmatch('?', '/', File::FNM_PATHNAME)
File.fnmatch('*', '/', File::FNM_PATHNAME)
File.fnmatch('[/]', '/', File::FNM_PATHNAME)

File.fnmatch('?', '?')
File.fnmatch('\a', 'a')
File.fnmatch('\a', '\a', File::FNM_NOESCAPE)
File.fnmatch('[?]', '?')

File.fnmatch('', '.profile')
File.fnmatch('
', '.profile', File::FNM_DOTMATCH)
File.fnmatch('.*', '.profile')

File.fnmatch('/*.rb', 'main.rb')
File.fnmatch('
/.rb', './main.rb')
File.fnmatch('**/
.rb', 'lib/song.rb')
File.fnmatch('.rb', 'main.rb')
File.fnmatch('
.rb', './main.rb')
File.fnmatch('**.rb', 'lib/song.rb')
File.fnmatch('*', 'dave/.profile')

File.fnmatch('/foo', 'a/b/c/foo', File::FNM_PATHNAME)
File.fnmatch('
/foo', '/a/b/c/foo', File::FNM_PATHNAME)
File.fnmatch('/foo', 'c:/a/b/c/foo', File::FNM_PATHNAME)
File.fnmatch('
/foo', 'a/.b/c/foo', File::FNM_PATHNAME)
File.fnmatch('**/foo', 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH)

def fnmatch(pattern, path, flags = 0) end

fnmatch?(pattern, path, flags = 0)

ftype(file_name) → string click to toggle source

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.ftype("/dev/tty")
File.ftype("/tmp/.X11-unix/X0")

static VALUE rb_file_s_ftype(VALUE klass, VALUE fname) { struct stat st;

FilePathValue(fname);
fname = rb_str_encode_ospath(fname);
if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
    rb_sys_fail_path(fname);
}

return rb_file_ftype(&st);

}

grpowned?(file_name) → true or false click to toggle source

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.

static VALUE rb_file_grpowned_p(VALUE obj, VALUE fname) { #ifndef _WIN32 struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
if (rb_group_member(st.st_gid)) return Qtrue;

#endif return Qfalse; }

identical?(file_1, file_2) → true or false click to toggle source

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")
p File.identical?("a", "./a")
File.link("a", "b") p File.identical?("a", "b")
File.symlink("a", "c") p File.identical?("a", "c")
open("d", "w") {} p File.identical?("a", "d")

static VALUE rb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2) { #ifndef _WIN32 struct stat st1, st2;

if (rb_stat(fname1, &st1) < 0) return Qfalse;
if (rb_stat(fname2, &st2) < 0) return Qfalse;
if (st1.st_dev != st2.st_dev) return Qfalse;
if (st1.st_ino != st2.st_ino) return Qfalse;
return Qtrue;

#else extern VALUE rb_w32_file_identical_p(VALUE, VALUE); return rb_w32_file_identical_p(fname1, fname2); #endif }

join(string, ...) → string click to toggle source

Returns a new string formed by joining the strings using "/".

File.join("usr", "mail", "gumby")

static VALUE rb_file_s_join(VALUE klass, VALUE args) { return rb_file_join(args); }

lchmod(mode_int, file_name, ...) → integer click to toggle source

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.

static VALUE rb_file_s_lchmod(int argc, VALUE *argv, VALUE _) { mode_t mode;

apply2args(1);
mode = NUM2MODET(*argv++);

return apply2files(lchmod_internal, argc, argv, &mode);

}

lchown(owner_int, group_int, file_name,..) → integer click to toggle source

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.

static VALUE rb_file_s_lchown(int argc, VALUE *argv, VALUE _) { struct chown_args arg;

apply2args(2);
arg.owner = to_uid(*argv++);
arg.group = to_gid(*argv++);

return apply2files(lchown_internal, argc, argv, &arg);

}

link(old_name, new_name) → 0 click to toggle source

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")
IO.readlines(".testfile")[0]

static VALUE rb_file_s_link(VALUE klass, VALUE from, VALUE to) { FilePathValue(from); FilePathValue(to); from = rb_str_encode_ospath(from); to = rb_str_encode_ospath(to);

if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
    sys_fail2(from, to);
}
return INT2FIX(0);

}

lstat(filepath) → stat click to toggle source

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
File.lstat('symlink').size

static VALUE rb_file_s_lstat(VALUE klass, VALUE fname) { #ifdef HAVE_LSTAT struct stat st;

FilePathValue(fname);
fname = rb_str_encode_ospath(fname);
if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
    rb_sys_fail_path(fname);
}
return rb_stat_new(&st);

#else return rb_file_s_stat(klass, fname); #endif }

lutime(atime, mtime, file_name, ...) → integer click to toggle source

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.

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

mkfifo(file_name, mode=0666) → 0 click to toggle source

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).

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

}

mtime(file_name) → time click to toggle source

Returns the modification time for the named file as a Time object.

file_name can be an IO object.

File.mtime("testfile")

static VALUE rb_file_s_mtime(VALUE klass, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) {
    int e = errno;
    FilePathValue(fname);
    rb_syserr_fail_path(e, fname);
}
return stat_mtime(&st);

}

new(path, mode = 'r', perm = 0666, **opts) → file click to toggle source

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:

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

}

open(path, mode = 'r', perm = 0666, **opts) → file click to toggle source

open(path, mode = 'r', perm = 0666, **opts) {|f| ... } → object

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 and returns the block’s value.

static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass) { VALUE io = rb_class_new_instance_kw(argc, argv, klass, RB_PASS_CALLED_KEYWORDS);

if (rb_block_given_p()) {
    return rb_ensure(rb_yield, io, io_close, io);
}

return io;

}

owned?(file_name) → true or false click to toggle source

Returns true if the named file exists and the effective used id of the calling process is the owner of the file.

file_name can be an IO object.

static VALUE rb_file_owned_p(VALUE obj, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
return RBOOL(st.st_uid == geteuid());

}

path(path) → string click to toggle source

Returns the string representation of the path

File.path(File::NULL)
File.path(Pathname.new("/tmp"))

static VALUE rb_file_s_path(VALUE klass, VALUE fname) { return rb_get_path(fname); }

pipe?(filepath) → true or false click to toggle source

Returns true if filepath points to a pipe, false otherwise:

File.mkfifo('tmp/fifo') File.pipe?('tmp/fifo') File.pipe?('t.txt')

static VALUE rb_file_pipe_p(VALUE obj, VALUE fname) { #ifdef S_IFIFO

ifndef S_ISFIFO

define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)

endif

struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
if (S_ISFIFO(st.st_mode)) return Qtrue;

#endif return Qfalse; }

readable?(file_name) → true or false click to toggle source

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.

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

readable_real?(file_name) → true or false click to toggle source

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.

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

readlink(link_name) → file_name click to toggle source

Returns the name of the file referenced by the given link. Not available on all platforms.

File.symlink("testfile", "link2test")
File.readlink("link2test")

static VALUE rb_file_s_readlink(VALUE klass, VALUE path) { return rb_readlink(path, rb_filesystem_encoding()); }

realdirpath(pathname [, dir_string]) → real_pathname click to toggle source

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

realpath(pathname [, dir_string]) → real_pathname click to toggle source

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

rename(old_name, new_name) → 0 click to toggle source

Renames the given file to the new name. Raises a SystemCallError if the file cannot be renamed.

File.rename("afile", "afile.bak")

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

}

setgid?(file_name) → true or false click to toggle source

Returns true if the named file has the setgid bit set.

file_name can be an IO object.

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

setuid?(file_name) → true or false click to toggle source

Returns true if the named file has the setuid bit set.

file_name can be an IO object.

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

size(file_name) → integer click to toggle source

Returns the size of file_name.

file_name can be an 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);

}

size?(file_name) → Integer or nil click to toggle source

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.

static VALUE rb_file_size_p(VALUE obj, VALUE fname) { struct stat st;

if (rb_stat(fname, &st) < 0) return Qnil;
if (st.st_size == 0) return Qnil;
return OFFT2NUM(st.st_size);

}

socket?(filepath) → true or false click to toggle source

Returns true if filepath points to a socket, false otherwise:

require 'socket' File.socket?(Socket.new(:INET, :STREAM)) File.socket?(File.new('t.txt'))

static VALUE rb_file_socket_p(VALUE obj, VALUE fname) { #ifndef S_ISSOCK

ifdef _S_ISSOCK

define S_ISSOCK(m) _S_ISSOCK(m)

else

ifdef _S_IFSOCK

define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)

else

ifdef S_IFSOCK

define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)

endif

endif

endif

#endif

#ifdef S_ISSOCK struct stat st;

if (rb_stat(fname, &st) < 0) return Qfalse;
if (S_ISSOCK(st.st_mode)) return Qtrue;

#endif

return Qfalse;

}

split(file_name) → array click to toggle source

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")

static VALUE rb_file_s_split(VALUE klass, VALUE path) { FilePathStringValue(path); /* get rid of converting twice */ return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef)); }

stat(filepath) → stat click to toggle source

Returns a File::Stat object for the file at filepath (see File::Stat):

File.stat('t.txt').class

static VALUE rb_file_s_stat(VALUE klass, VALUE fname) { struct stat st;

FilePathValue(fname);
fname = rb_str_encode_ospath(fname);
if (stat_without_gvl(RSTRING_PTR(fname), &st) < 0) {
    rb_sys_fail_path(fname);
}
return rb_stat_new(&st);

}

sticky?(file_name) → true or false click to toggle source

Returns true if the named file has the sticky bit set.

file_name can be an IO object.

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

symlink(old_name, new_name) → 0 click to toggle source

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")

static VALUE rb_file_s_symlink(VALUE klass, VALUE from, VALUE to) { FilePathValue(from); FilePathValue(to); from = rb_str_encode_ospath(from); to = rb_str_encode_ospath(to);

if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
    sys_fail2(from, to);
}
return INT2FIX(0);

}

symlink?(filepath) → true or false click to toggle source

Returns true if filepath points to a symbolic link, false otherwise:

symlink = File.symlink('t.txt', 'symlink') File.symlink?('symlink') File.symlink?('t.txt')

static VALUE rb_file_symlink_p(VALUE obj, VALUE fname) { #ifndef S_ISLNK

ifdef _S_ISLNK

define S_ISLNK(m) _S_ISLNK(m)

else

ifdef _S_IFLNK

define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)

else

ifdef S_IFLNK

define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)

endif

endif

endif

#endif

#ifdef S_ISLNK struct stat st;

FilePathValue(fname);
fname = rb_str_encode_ospath(fname);
if (lstat_without_gvl(StringValueCStr(fname), &st) < 0) return Qfalse;
if (S_ISLNK(st.st_mode)) return Qtrue;

#endif

return Qfalse;

}

truncate(file_name, integer) → 0 click to toggle source

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")
f.close
File.truncate("out", 5)
File.size("out")

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

}

umask() → integer click to toggle source

umask(integer) → integer

Returns the current umask value for this process. If the optional argument is given, set the umask to that value and return the previous value. Umask values are subtracted from the default permissions, so a umask of 0222 would make a file read-only for everyone.

File.umask(0006)
File.umask

static VALUE rb_file_s_umask(int argc, VALUE *argv, VALUE _) { mode_t omask = 0;

switch (argc) {
  case 0:
    omask = umask(0);
    umask(omask);
    break;
  case 1:
    omask = umask(NUM2MODET(argv[0]));
    break;
  default:
    rb_error_arity(argc, 0, 1);
}
return MODET2NUM(omask);

}

delete(file_name, ...) → integer click to toggle source

unlink(file_name, ...) → integer

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. Since the underlying implementation relies on the unlink(2) system call, the type of exception raised depends on its error type (see linux.die.net/man/2/unlink) and has the form of e.g. Errno::ENOENT.

See also Dir::rmdir.

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

utime(atime, mtime, file_name, ...) → integer click to toggle source

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.

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

world_readable?(file_name) → integer or nil click to toggle source

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")
m = File.world_readable?("/etc/passwd") sprintf("%o", m)

static VALUE rb_file_world_readable_p(VALUE obj, VALUE fname) { #ifdef S_IROTH struct stat st;

if (rb_stat(fname, &st) < 0) return Qnil;
if ((st.st_mode & (S_IROTH)) == S_IROTH) {
    return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
}

#endif return Qnil; }

world_writable?(file_name) → integer or nil click to toggle source

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")
m = File.world_writable?("/tmp") sprintf("%o", m)

static VALUE rb_file_world_writable_p(VALUE obj, VALUE fname) { #ifdef S_IWOTH struct stat st;

if (rb_stat(fname, &st) < 0) return Qnil;
if ((st.st_mode & (S_IWOTH)) == S_IWOTH) {
    return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
}

#endif return Qnil; }

writable?(file_name) → true or false click to toggle source

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.

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

writable_real?(file_name) → true or false click to toggle source

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.

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

zero?(file_name) → true or false click to toggle source

Returns true if the named file exists and has a zero size.

file_name can be an IO object.

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

atime → time click to toggle source

Returns the last access time (a Time object) for file, or epoch if file has not been accessed.

File.new("testfile").atime

static VALUE rb_file_atime(VALUE obj) { rb_io_t *fptr; struct stat st;

GetOpenFile(obj, fptr);
if (fstat(fptr->fd, &st) == -1) {
    rb_sys_fail_path(fptr->pathv);
}
return stat_atime(&st);

}

birthtime → time click to toggle source

Returns the birth time for file.

File.new("testfile").birthtime

If the platform doesn’t have birthtime, raises NotImplementedError.

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

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

}

chmod(mode_int) → 0 click to toggle source

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)

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->fd, mode) == -1) { if (HAVE_FCHMOD || errno != ENOSYS) rb_sys_fail_path(fptr->pathv); } else { if (!HAVE_FCHMOD) return INT2FIX(0); } #endif #if !defined HAVE_FCHMOD || !HAVE_FCHMOD if (NIL_P(fptr->pathv)) return Qnil; path = rb_str_encode_ospath(fptr->pathv); if (rb_chmod(RSTRING_PTR(path), mode) == -1) rb_sys_fail_path(fptr->pathv); #endif

return INT2FIX(0);

}

chown(owner_int, group_int ) → 0 click to toggle source

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

}

ctime → time click to toggle source

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

static VALUE rb_file_ctime(VALUE obj) { rb_io_t *fptr; struct stat st;

GetOpenFile(obj, fptr);
if (fstat(fptr->fd, &st) == -1) {
    rb_sys_fail_path(fptr->pathv);
}
return stat_ctime(&st);

}

flock(locking_constant) → 0 or false click to toggle source

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:

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

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

}

lstat → stat click to toggle source

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
f.lstat.size

static VALUE rb_file_lstat(VALUE obj) { #ifdef HAVE_LSTAT rb_io_t *fptr; struct stat st; VALUE path;

GetOpenFile(obj, fptr);
if (NIL_P(fptr->pathv)) return Qnil;
path = rb_str_encode_ospath(fptr->pathv);
if (lstat_without_gvl(RSTRING_PTR(path), &st) == -1) {
    rb_sys_fail_path(fptr->pathv);
}
return rb_stat_new(&st);

#else return rb_io_stat(obj); #endif }

mtime → time click to toggle source

Returns the modification time for file.

File.new("testfile").mtime

static VALUE rb_file_mtime(VALUE obj) { rb_io_t *fptr; struct stat st;

GetOpenFile(obj, fptr);
if (fstat(fptr->fd, &st) == -1) {
    rb_sys_fail_path(fptr->pathv);
}
return stat_mtime(&st);

}

size → integer click to toggle source

Returns the size of file in bytes.

File.new("testfile").size

static VALUE file_size(VALUE self) { return OFFT2NUM(rb_file_size(self)); }

truncate(integer) → 0 click to toggle source

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")
f.truncate(5)
f.close()
File.size("out")

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

}