123456789_123456789_123456789_123456789_123456789_

Class: File

Relationships & Source Files
Namespace Children
Modules:
Classes:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::IO
Instance Chain:
Inherits: IO
Defined in: file.c,
dir.c,
io.c

Overview

A File is an abstraction of any file object accessible by the program and is closely associated with class ::IO. File includes the methods of module ::FileTest as class methods, allowing you to write (for example) File.exist?("foo").

In the description of File methods, permission bits are a platform-specific set of bits that indicate permissions of a file. On Unix-based systems, permissions are viewed as a set of three octets, for the owner, the group, and the rest of the world. For each of these entities, permissions may be set to read, write, or execute the file:

The permission bits 0644 (in octal) would thus be interpreted as read/write for owner, and read-only for group and other. Higher-order bits may also be used to indicate the type of file (plain, directory, pipe, socket, and so on) and various other special features. If the permissions are for a directory, the meaning of the execute bit changes; when set the directory can be searched.

On non-Posix operating systems, there may be only the ability to make a file read-only or read-write. In this case, the remaining permission bits will be synthesized to resemble typical values. For instance, on Windows NT the default permission bits are 0644, which means read/write for owner, read-only for all others. The only change that can be made is to make the file read-only, which is reported as 0444.

Various constants for the methods in File can be found in Constants.

Constant Summary

Constants - Included

APPEND, BINARY, CREAT, DIRECT, DSYNC, EXCL, LOCK_EX, LOCK_NB, LOCK_SH, LOCK_UN, NOATIME, NOCTTY, NOFOLLOW, NONBLOCK, NULL, RDONLY, RDWR, RSYNC, SHARE_DELETE, SYNC, TMPFILE, TRUNC, WRONLY

::IO - Inherited

SEEK_CUR, SEEK_DATA, SEEK_END, SEEK_HOLE, SEEK_SET

Class Attribute Summary

Class Method Summary

::IO - Inherited

.binread

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file).

.binwrite

Same as IO.write except opening the file in binary mode and ASCII-8BIT encoding (“wb:ASCII-8BIT”).

.copy_stream

copy_stream copies src to dst.

.for_fd

Synonym for IO.new.

.foreach

Executes the block for every line in the named I/O port, where lines are separated by sep.

.open

Alias for .open.

.pipe

::IO.pipe(…) {|read_io, write_io| … }

.popen

Runs the specified command as a subprocess; the subprocess's standard input and output will be connected to the returned ::IO object.

.read

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file).

.readlines

Reads the entire file specified by name as individual lines, and returns those lines in an array.

.select

Alias for Kernel.select.

.sysopen

Opens the given path, returning the underlying file descriptor as a ::Integer.

.try_convert

Try to convert obj into an ::IO, using to_io method.

.write

Opens the file, optionally seeks to the given offset, writes string, then returns the length written.

.new

Instance Attribute Summary

::IO - Inherited

#autoclose=

Sets auto-close flag.

#autoclose?

Returns true if the underlying file descriptor of ios will be closed automatically at its finalization, otherwise false.

#binmode

Puts ios into binary mode.

#binmode?

Returns true if ios is binmode.

#close_on_exec=

Sets a close-on-exec flag.

#close_on_exec?

Returns true if ios will be closed on exec.

#closed?

Returns true if ios is completely closed (for duplex streams, both reader and writer), false otherwise.

#eof

Returns true if ios is at end of file that means there are no more data to read.

#eof?

Alias for IO#eof.

#isatty

Alias for IO#tty?.

#lineno

Returns the current line number in ios.

#lineno=

Manually sets the current line number to the given value.

#pos

Returns the current offset (in bytes) of ios.

#pos=

Seeks to the given position (in bytes) in ios.

#sync

Returns the current “sync mode'' of ios.

#sync=

Sets the “sync mode'' to true or false.

#tell

Alias for IO#pos.

#tty?

Returns true if ios is associated with a terminal device (tty), false otherwise.

Instance Method Summary

::IO - Inherited

#<<

::String Output—Writes obj to ios.

#advise

Announce an intention to access data from the current file in a specific pattern.

#bytes

This is a deprecated alias for each_byte.

#chars

This is a deprecated alias for each_char.

#close

Closes ios and flushes any pending writes to the operating system.

#close_read

Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe).

#close_write

Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe).

#codepoints

This is a deprecated alias for each_codepoint.

#each

ios.each_line(sep=$/ [, getline_args]) {|line| block } -> ios.

#each_byte

Calls the given block once for each byte (0..255) in ios, passing the byte as an argument.

#each_char

Calls the given block once for each character in ios, passing the character as an argument.

#each_codepoint

Passes the ::Integer ordinal of each character in ios, passing the codepoint as an argument.

#each_line

Alias for IO#each.

#external_encoding

Returns the ::Encoding object that represents the encoding of the file.

#fcntl

Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams.

#fdatasync

Immediately writes all buffered data in ios to disk.

#fileno

Alias for IO#to_i.

#flush

Flushes any buffered data within ios to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well).

#fsync

Immediately writes all buffered data in ios to disk.

#getbyte

Gets the next 8-bit byte (0..255) from ios.

#getc

Reads a one-character string from ios.

#gets

Reads the next “line'' from the I/O stream; lines are separated by sep.

#initialize

Returns a new ::IO object (a stream) for the given integer file descriptor fd and mode string.

#inspect

Return a string describing this ::IO object.

#internal_encoding

Returns the ::Encoding of the internal string if conversion is specified.

#ioctl

Provides a mechanism for issuing low-level commands to control or query I/O devices.

#lines

This is a deprecated alias for each_line.

#pid

Returns the process ID of a child process associated with ios.

#pread

Reads maxlen bytes from ios using the pread system call and returns them as a string without modifying the underlying descriptor offset.

#print

Writes the given object(s) to ios.

#printf

Formats and writes to ios, converting parameters under control of the format string.

#putc

If obj is ::Numeric, write the character whose code is the least-significant byte of obj.

#puts

Writes the given object(s) to ios.

#pwrite

Writes the given string to ios at offset using pwrite() system call.

#read

Reads length bytes from the I/O stream.

#read_nonblock

Reads at most maxlen bytes from ios using the read(2) system call after O_NONBLOCK is set for the underlying file descriptor.

#readbyte

Reads a byte as with IO#getbyte, but raises an ::EOFError on end of file.

#readchar

Reads a one-character string from ios.

#readline

Reads a line as with IO#gets, but raises an ::EOFError on end of file.

#readlines

Reads all of the lines in ios, and returns them in an array.

#readpartial

Reads at most maxlen bytes from the I/O stream.

#reopen

Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path.

#rewind

Positions ios to the beginning of input, resetting lineno to zero.

#seek

Seeks to a given offset anInteger in the stream according to the value of whence:

#set_encoding

If single argument is specified, read string from io is tagged with the encoding specified.

#stat

Returns status information for ios as an object of type Stat.

#sysread

Reads maxlen bytes from ios using a low-level read and returns them as a string.

#sysseek

Seeks to a given offset in the stream according to the value of whence (see IO#seek for values of whence).

#syswrite

Writes the given string to ios using a low-level write.

#to_i

Returns an integer representing the numeric file descriptor for ios.

#to_io

Returns ios.

#ungetbyte

Pushes back bytes (passed as a parameter) onto ios, such that a subsequent buffered read will return it.

#ungetc

Pushes back one character (passed as a parameter) onto ios, such that a subsequent buffered character read will return it.

#write

Writes the given strings to ios.

#write_nonblock

Writes the given string to ios using the write(2) system call after O_NONBLOCK is set for the underlying file descriptor.

#initialize_copy, #__read_nonblock, #__write_nonblock

::Enumerable - Included

#all?

Passes each element of the collection to the given block.

#any?

Passes each element of the collection to the given block.

#chunk

Enumerates over the items, chunking them together based on the return value of the block.

#chunk_while

Creates an enumerator for each chunked elements.

#collect

Alias for Enumerable#map.

#collect_concat
#count

Returns the number of items in enum through enumeration.

#cycle

Calls block for each element of enum repeatedly n times or forever if none or nil is given.

#detect

Alias for Enumerable#find.

#drop

Drops first n elements from enum, and returns rest elements in an array.

#drop_while

Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements.

#each_cons

Iterates the given block for each array of consecutive <n> elements.

#each_entry

Calls block once for each element in self, passing that element as a parameter, converting multiple values from yield to an array.

#each_slice

Iterates the given block for each slice of <n> elements.

#each_with_index

Calls block with two arguments, the item and its index, for each item in enum.

#each_with_object

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

#entries

Alias for Enumerable#to_a.

#find

Passes each entry in enum to block.

#find_all
#find_index

Compares each entry in enum with value or passes to block.

#first

Returns the first element, or the first n elements, of the enumerable.

#flat_map

Returns a new array with the concatenated results of running block once for every element in enum.

#grep

Returns an array of every element in enum for which Pattern === element.

#grep_v

Inverted version of Enumerable#grep.

#group_by

Groups the collection by result of the block.

#include?
#inject

Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.

#lazy

Returns a lazy enumerator, whose methods map/collect, flat_map/collect_concat, select/find_all, reject, grep, grep_v, zip, take, take_while, drop, and drop_while enumerate values only on an as-needed basis.

#map

Returns a new array with the results of running block once for every element in enum.

#max

Returns the object in enum with the maximum value.

#max_by

Returns the object in enum that gives the maximum value from the given block.

#member?

Returns true if any member of enum equals obj.

#min

Returns the object in enum with the minimum value.

#min_by

Returns the object in enum that gives the minimum value from the given block.

#minmax

Returns a two element array which contains the minimum and the maximum value in the enumerable.

#minmax_by

Returns a two element array containing the objects in enum that correspond to the minimum and maximum values respectively from the given block.

#none?

Passes each element of the collection to the given block.

#one?

Passes each element of the collection to the given block.

#partition

Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.

#reduce
#reject

Returns an array for all elements of enum for which the given block returns false.

#reverse_each

Builds a temporary array and traverses that array in reverse order.

#select

Returns an array containing all elements of enum for which the given block returns a true value.

#slice_after

Creates an enumerator for each chunked elements.

#slice_before

Creates an enumerator for each chunked elements.

#slice_when

Creates an enumerator for each chunked elements.

#sort

Returns an array containing the items in enum sorted.

#sort_by

Sorts enum using a set of keys generated by mapping the values in enum through the given block.

#sum

Returns the sum of elements in an ::Enumerable.

#take

Returns first n elements from enum.

#take_while

Passes elements to the block until the block returns nil or false, then stops iterating and returns an array of all prior elements.

#to_a

Returns an array containing the items in enum.

#to_h

Returns the result of interpreting enum as a list of [key, value] pairs.

#uniq

Returns a new array by removing duplicate values in self.

#zip

Takes one element from enum and merges corresponding elements from each args.

Constructor Details

.new(filename, mode="r" [, opt]) ⇒ File .new(filename [, mode [, perm]] [, opt]) ⇒ File

Opens the file named by filename according to the given mode and returns a new File object.

See IO.new for a description of mode and opt.

If a file is being created, permission bits may be given in perm. These mode and permission bits are platform dependent; on Unix systems, see open(2) and chmod(2) man pages for details.

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= about sync mode.

Examples

f = File.new("testfile", "r")
f = File.new("newfile",  "w+")
f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
[ GitHub ]

  
# File 'io.c', line 8198

static VALUE
rb_file_initialize(int argc, VALUE *argv, VALUE io)
{
    if (RFILE(io)->fptr) {
	rb_raise(rb_eRuntimeError, "reinitializing File");
    }
    if (0 < argc && argc < 3) {
	VALUE fd = rb_check_to_int(argv[0]);

	if (!NIL_P(fd)) {
	    argv[0] = fd;
	    return rb_io_initialize(argc, argv, io);
	}
    }
    rb_open_file(argc, argv, io);

    return io;
}

Class Attribute Details

.directory?(file_name) ⇒ Boolean (readonly)

Alias for Dir.exist?.

Class Method Details

.absolute_path(file_name [, dir_string] ) ⇒ File

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. If the given pathname starts with a “~'' it is NOT expanded, it is treated as a normal directory name.

File.absolute_path("~oracle/bin")       #=> "<relative_path>/~oracle/bin"
[ GitHub ]

  
# File 'file.c', line 3930

VALUE
rb_file_s_absolute_path(int argc, const VALUE *argv)
{
    rb_check_arity(argc, 1, 2);
    return rb_file_absolute_path(argv[0], argc > 1 ? argv[1] : Qnil);
}

.atime(file_name) ⇒ Time

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

file_name can be an ::IO object.

File.atime("testfile")   #=> Wed Apr 09 08:51:48 CDT 2003
[ GitHub ]

  
# File 'file.c', line 2136

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

Returns the last component of the filename given in file_name (after first stripping trailing separators), which can be formed using both SEPARATOR and ALT_SEPARATOR as the separator when ALT_SEPARATOR is not nil. If suffix is given and present at the end of file_name, it is removed. If suffix is “.*”, any extension will be removed.

File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"
File.basename("/home/gumby/work/ruby.rb", ".*")    #=> "ruby"
[ GitHub ]

  
# File 'file.c', line 4328

static VALUE
rb_file_s_basename(int argc, VALUE *argv)
{
    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);
    OBJ_INFECT(basename, fname);
    return basename;
}

.birthtime(file_name) ⇒ Time

Returns the birth time for the named file.

file_name can be an ::IO object.

File.birthtime("testfile")   #=> Wed Apr 09 08:53:13 CDT 2003

If the platform doesn't have birthtime, raises ::NotImplementedError.

[ GitHub ]

  
# File 'file.c', line 2291

static VALUE
rb_file_s_birthtime(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_birthtime(&st);
}

.blockdev?(file_name) ⇒ Boolean

Returns true if the named file is a block device.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1569

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?(file_name) ⇒ Boolean

Returns true if the named file is a character device.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1598

static VALUE
rb_file_chardev_p(VALUE obj, VALUE fname)
{
#ifndef S_ISCHR
#   define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#endif

    struct stat st;

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

    return Qfalse;
}

.chmod(mode_int, file_name, ... ) ⇒ Integer

Changes permission bits on the named file(s) to the bit pattern represented by mode_int. Actual effects are operating system dependent (see the beginning of this section). On Unix systems, see chmod(2) for details. Returns the number of files processed.

File.chmod(0644, "testfile", "out")   #=> 2
[ GitHub ]

  
# File 'file.c', line 2381

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

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

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

.chown(owner_int, group_int, file_name,... ) ⇒ Integer

Changes the owner and group of the named file(s) to the given numeric owner and group id's. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file's group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Returns the number of files processed.

File.chown(nil, 100, "testfile")
[ GitHub ]

  
# File 'file.c', line 2512

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

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

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

.ctime(file_name) ⇒ Time

Returns the change time for the named file (the time at which directory information about the file was changed, not the file itself).

file_name can be an ::IO object.

Note that on Windows (NTFS), returns creation time (birth time).

File.ctime("testfile")   #=> Wed Apr 09 08:53:13 CDT 2003
[ GitHub ]

  
# File 'file.c', line 2237

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

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

.delete(file_name, ...) ⇒ Integer .unlink(file_name, ...) ⇒ Integer
Also known as: .unlink

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.

[ GitHub ]

  
# File 'file.c', line 2983

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

.dirname(file_name) ⇒ dir_name

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 SEPARATOR and ALT_SEPARATOR as the separator when ALT_SEPARATOR is not nil.

File.dirname("/home/gumby/work/ruby.rb")   #=> "/home/gumby/work"
[ GitHub ]

  
# File 'file.c', line 4386

static VALUE
rb_file_s_dirname(VALUE klass, VALUE fname)
{
    return rb_file_dirname(fname);
}

.empty?(file_name) ⇒ Boolean

Alias for FileTest#zero?. Returns true if the named file exists and has a zero size.

file_name can be an ::IO object.

.executable?(file_name) ⇒ Boolean

Returns true if the named file is executable by the effective user and group id of this process. See eaccess(3).

[ GitHub ]

  
# File 'file.c', line 1791

static VALUE
rb_file_executable_p(VALUE obj, VALUE fname)
{
    if (rb_eaccess(fname, X_OK) < 0) return Qfalse;
    return Qtrue;
}

.executable_real?(file_name) ⇒ Boolean

Returns true if the named file is executable by the real user and group id of this process. See access(3).

[ GitHub ]

  
# File 'file.c', line 1806

static VALUE
rb_file_executable_real_p(VALUE obj, VALUE fname)
{
    if (rb_access(fname, X_OK) < 0) return Qfalse;
    return Qtrue;
}

.exist?(file_name) ⇒ Boolean

Return true if the named file exists.

file_name can be an ::IO object.

“file exists” means that stat() or fstat() system call is successful.

[ GitHub ]

  
# File 'file.c', line 1624

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

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

.exists?(file_name) ⇒ Boolean

Deprecated method. Don't use.

[ GitHub ]

  
# File 'file.c', line 1639

static VALUE
rb_file_exists_p(VALUE obj, VALUE fname)
{
    const char *s = "FileTest#";
    if (obj == rb_mFileTest) {
	s = "FileTest.";
    }
    else if (obj == rb_cFile ||
	     (RB_TYPE_P(obj, T_CLASS) &&
	      RTEST(rb_class_inherited_p(obj, rb_cFile)))) {
	s = "File.";
    }
    rb_warning("%sexists? is a deprecated name, use %sexist? instead", s, s);
    return rb_file_exist_p(obj, fname);
}

.expand_path(file_name [, dir_string] ) ⇒ File

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")           #=> "/home/oracle/bin"

A simple example of using dir_string is as follows.

File.expand_path("ruby", "/usr/bin")      #=> "/usr/bin/ruby"

A more complex example which also resolves parent directory is as follows. Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.

File.expand_path("../../lib/mygem.rb", __FILE__)
#=> ".../path/to/project/lib/mygem.rb"

So first it resolves the parent of __FILE__, that is bin/, then go to the parent, the root of the project and appends lib/mygem.rb.

[ GitHub ]

  
# File 'file.c', line 3903

VALUE
rb_file_s_expand_path(int argc, const VALUE *argv)
{
    rb_check_arity(argc, 1, 2);
    return rb_file_expand_path(argv[0], argc > 1 ? argv[1] : Qnil);
}

.extname(path) ⇒ String

Returns the extension (the portion of file name in .path starting from the last period).

If .path is a dotfile, or starts with a period, then the starting dot is not dealt with the start of the extension.

An empty string will also be returned when the period is the last character in .path.

File.extname("test.rb")         #=> ".rb"
File.extname("a/b/d/test.rb")   #=> ".rb"
File.extname(".a/b/d/test.rb")  #=> ".rb"
File.extname("foo.")            #=> ""
File.extname("test")            #=> ""
File.extname(".profile")        #=> ""
File.extname(".profile.sh")     #=> ".sh"
[ GitHub ]

  
# File 'file.c', line 4523

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! */
    OBJ_INFECT(extname, fname);
    return extname;
}

.file?(file) ⇒ Boolean

Returns true if the named file exists and is a regular file.

file can be an ::IO object.

If the file argument is a symbolic link, it will resolve the symbolic link and use the file referenced by the link.

[ GitHub ]

  
# File 'file.c', line 1829

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

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

.fnmatch(pattern, path, [flags]) ⇒ Boolean .fnmatch?(pattern, path, [flags]) ⇒ Boolean
Also known as: .fnmatch?

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 files 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')        #=> true  # match entire string
File.fnmatch('cat',       'category')   #=> false # only match partial string

File.fnmatch('c{at,ub}s', 'cats')                    #=> false # { } isn't supported by default
File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true  # { } is supported on FNM_EXTGLOB

File.fnmatch('c?t',     'cat')          #=> true  # '?' match only 1 character
File.fnmatch('c??t',    'cat')          #=> false # ditto
File.fnmatch('c*',      'cats')         #=> true  # '*' match 0 or more characters
File.fnmatch('c*t',     'c/a/b/t')      #=> true  # ditto
File.fnmatch('ca[a-z]', 'cat')          #=> true  # inclusive bracket expression
File.fnmatch('ca[^t]',  'cat')          #=> false # exclusive bracket expression ('^' or '!')

File.fnmatch('cat', 'CAT')                     #=> false # case sensitive
File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true  # case insensitive

File.fnmatch('?',   '/', File::FNM_PATHNAME)  #=> false # wildcard doesn't match '/' on FNM_PATHNAME
File.fnmatch('*',   '/', File::FNM_PATHNAME)  #=> false # ditto
File.fnmatch('[/]', '/', File::FNM_PATHNAME)  #=> false # ditto

File.fnmatch('\?',   '?')                       #=> true  # escaped wildcard becomes ordinary
File.fnmatch('\a',   'a')                       #=> true  # escaped ordinary remains ordinary
File.fnmatch('\a',   '\a', File::FNM_NOESCAPE)  #=> true  # FNM_NOESCAPE makes '\' ordinary
File.fnmatch('[\?]', '?')                       #=> true  # can escape inside bracket expression

File.fnmatch('*',   '.profile')                      #=> false # wildcard doesn't match leading
File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)  #=> true  # period by default.
File.fnmatch('.*',  '.profile')                      #=> true

rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
File.fnmatch(rbfiles, 'main.rb')                    #=> false
File.fnmatch(rbfiles, './main.rb')                  #=> false
File.fnmatch(rbfiles, 'lib/song.rb')                #=> true
File.fnmatch('**.rb', 'main.rb')                    #=> true
File.fnmatch('**.rb', './main.rb')                  #=> false
File.fnmatch('**.rb', 'lib/song.rb')                #=> true
File.fnmatch('*',           'dave/.profile')                      #=> true

pattern = '*' '/' '*'
File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME)  #=> false
File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true

pattern = '**' '/' 'foo'
File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME)     #=> true
File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME)    #=> true
File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME)  #=> true
File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME)    #=> false
File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
[ GitHub ]

  
# File 'dir.c', line 3011

static VALUE
file_s_fnmatch(int argc, VALUE *argv, VALUE obj)
{
    VALUE pattern, path;
    VALUE rflags;
    int flags;

    if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
	flags = NUM2INT(rflags);
    else
	flags = 0;

    StringValueCStr(pattern);
    FilePathStringValue(path);

    if (flags & FNM_EXTGLOB) {
	struct brace_args args;

	args.value = path;
	args.flags = flags;
	if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace,
			      (VALUE)&args, rb_enc_get(pattern), pattern) > 0)
	    return Qtrue;
    }
    else {
	rb_encoding *enc = rb_enc_compatible(pattern, path);
	if (!enc) return Qfalse;
	if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0)
	    return Qtrue;
    }
    RB_GC_GUARD(pattern);

    return Qfalse;
}

.fnmatch(pattern, path, [flags]) ⇒ Boolean .fnmatch?(pattern, path, [flags]) ⇒ Boolean

Alias for .fnmatch.

.ftype(file_name) ⇒ String

Identifies the type of the named file; the return string is one of “file'', “directory'', “characterSpecial'', “blockSpecial'', “fifo'', “link'', “socket'', or “unknown''.

File.ftype("testfile")            #=> "file"
File.ftype("/dev/tty")            #=> "characterSpecial"
File.ftype("/tmp/.X11-unix/X0")   #=> "socket"
[ GitHub ]

  
# File 'file.c', line 2110

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

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

    return rb_file_ftype(&st);
}

.grpowned?(file_name) ⇒ Boolean

Returns true if the named file exists and the effective group id of the calling process is the owner of the file. Returns false on Windows.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1921

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

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

.identical?(file_1, file_2) ⇒ Boolean

Returns true if the named files are identical.

file_1 and file_2 can be an ::IO object.

open("a", "w") {}
p File.identical?("a", "a")      #=> true
p File.identical?("a", "./a")    #=> true
File.link("a", "b")
p File.identical?("a", "b")      #=> true
File.symlink("a", "c")
p File.identical?("a", "c")      #=> true
open("d", "w") {}
p File.identical?("a", "d")      #=> false
[ GitHub ]

  
# File 'file.c', line 2015

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

    if (rb_stat(fname1, &st1) < 0) return Qfalse;
    if (rb_stat(fname2, &st2) < 0) return Qfalse;
    if (st1.st_dev != st2.st_dev) return Qfalse;
    if (st1.st_ino != st2.st_ino) return Qfalse;
    return Qtrue;
#else
    extern VALUE rb_w32_file_identical_p(VALUE, VALUE);
    return rb_w32_file_identical_p(fname1, fname2);
#endif
}

.join(string, ...) ⇒ String

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

File.join("usr", "mail", "gumby")   #=> "usr/mail/gumby"
[ GitHub ]

  
# File 'file.c', line 4663

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

.lchmod(mode_int, file_name, ...) ⇒ Integer

Equivalent to .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.

[ GitHub ]

  
# File 'file.c', line 2453

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

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

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

.lchown(owner_int, group_int, file_name,..) ⇒ Integer

Equivalent to .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.

[ GitHub ]

  
# File 'file.c', line 2584

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

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

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

.lstat(file_name) ⇒ stat

Same as .stat, but does not follow the last symbolic link. Instead, reports on the link itself.

File.symlink("testfile", "link2test")   #=> 0
File.stat("testfile").size              #=> 66
File.lstat("link2test").size            #=> 8
File.stat("link2test").size             #=> 66
[ GitHub ]

  
# File 'file.c', line 1224

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

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

.lutime(atime, mtime, file_name,...) ⇒ Integer

Sets the access and modification times of each named file to the first two arguments. If a file is a symlink, this method acts upon the link itself as opposed to its referent; for the inverse behavior, see .utime. Returns the number of file names in the argument list.

[ GitHub ]

  
# File 'file.c', line 2781

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

.mkfifo(file_name, mode = 0666) ⇒ 0

Creates a FIFO special file with name file_name. mode specifies the FIFO's permissions. It is modified by the process's umask in the usual way: the permissions of the created file are (mode & ~umask).

[ GitHub ]

  
# File 'file.c', line 5809

static VALUE
rb_file_s_mkfifo(int argc, VALUE *argv)
{
    VALUE path;
    struct mkfifo_arg ma;

    ma.mode = 0666;
    rb_check_arity(argc, 1, 2);
    if (argc > 1) {
	ma.mode = NUM2MODET(argv[1]);
    }
    path = argv[0];
    FilePathValue(path);
    path = rb_str_encode_ospath(path);
    ma.path = RSTRING_PTR(path);
    if (rb_thread_call_without_gvl(nogvl_mkfifo, &ma, RUBY_UBF_IO, 0)) {
	rb_sys_fail_path(path);
    }
    return INT2FIX(0);
}

.mtime(file_name) ⇒ Time

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

file_name can be an ::IO object.

File.mtime("testfile")   #=> Tue Apr 08 12:58:04 CDT 2003
[ GitHub ]

  
# File 'file.c', line 2185

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

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

.open(filename, mode="r" [, opt]) ⇒ File .open(filename [, mode [, perm]] [, opt]) ⇒ File .open(filename, mode="r" [, opt]) {|file| ... } ⇒ Object .open(filename [, mode [, perm]] [, opt]) {|file| ... } ⇒ Object

With no associated block, open is a synonym for .new. If the optional code block is given, it will be passed the opened file as an argument and the File object will automatically be closed when the block terminates. The value of the block will be returned from open.

If a file is being created, its initial permissions may be set using the perm parameter. See .new for further discussion.

See IO.new for a description of the mode and opt parameters.

[ GitHub ]

  
# File 'io.c', line 6890

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

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

    return io;
}

.owned?(file_name) ⇒ Boolean

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

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1890

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

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

.path(path) ⇒ String

Returns the string representation of the path

File.path("/dev/null")          #=> "/dev/null"
File.path(Pathname.new("/tmp")) #=> "/tmp"
[ GitHub ]

  
# File 'file.c', line 4552

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

.pipe?(file_name) ⇒ Boolean

Returns true if the named file is a pipe.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1471

static VALUE
rb_file_pipe_p(VALUE obj, VALUE fname)
{
#ifdef S_IFIFO
#  ifndef S_ISFIFO
#    define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#  endif

    struct stat st;

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

#endif
    return Qfalse;
}

.readable?(file_name) ⇒ Boolean

Returns true if the named file is readable by the effective user and group id of this process. See eaccess(3).

[ GitHub ]

  
# File 'file.c', line 1663

static VALUE
rb_file_readable_p(VALUE obj, VALUE fname)
{
    if (rb_eaccess(fname, R_OK) < 0) return Qfalse;
    return Qtrue;
}

.readable_real?(file_name) ⇒ Boolean

Returns true if the named file is readable by the real user and group id of this process. See access(3).

[ GitHub ]

  
# File 'file.c', line 1678

static VALUE
rb_file_readable_real_p(VALUE obj, VALUE fname)
{
    if (rb_access(fname, R_OK) < 0) return Qfalse;
    return Qtrue;
}

.realdirpath(pathname [, dir_string]) ⇒ real_pathname

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.

[ GitHub ]

  
# File 'file.c', line 4202

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

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.

[ GitHub ]

  
# File 'file.c', line 4181

static VALUE
rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
{
    VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
    VALUE path = argv[0];
    FilePathValue(path);
    return rb_realpath_internal(basedir, path, 1);
}

.rename(old_name, new_name) ⇒ 0

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

File.rename("afile", "afile.bak")   #=> 0
[ GitHub ]

  
# File 'file.c', line 3012

static VALUE
rb_file_s_rename(VALUE klass, VALUE from, VALUE to)
{
    struct rename_args ra;
    VALUE f, t;

    FilePathValue(from);
    FilePathValue(to);
    f = rb_str_encode_ospath(from);
    t = rb_str_encode_ospath(to);
    ra.src = StringValueCStr(f);
    ra.dst = StringValueCStr(t);
#if defined __CYGWIN__
    errno = 0;
#endif
    if ((int)(VALUE)rb_thread_call_without_gvl(no_gvl_rename, &ra,
					 RUBY_UBF_IO, 0) < 0) {
	int e = errno;
#if defined DOSISH
	switch (e) {
	  case EEXIST:
	    if (chmod(ra.dst, 0666) == 0 &&
		unlink(ra.dst) == 0 &&
		rename(ra.src, ra.dst) == 0)
		return INT2FIX(0);
	}
#endif
	syserr_fail2(e, from, to);
    }

    return INT2FIX(0);
}

.setgid?(file_name) ⇒ Boolean

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

[ GitHub ]

  
# File 'file.c', line 1969

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

.setuid?(file_name) ⇒ Boolean

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

[ GitHub ]

  
# File 'file.c', line 1952

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

.size(file_name) ⇒ Integer

Returns the size of file_name.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 2041

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

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

.size?(file_name) ⇒ Integer?

Returns nil if file_name doesn't exist or has zero size, the size of the file otherwise.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1869

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?(file_name) ⇒ Boolean

Returns true if the named file is a socket.

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1533

static VALUE
rb_file_socket_p(VALUE obj, VALUE fname)
{
#ifndef S_ISSOCK
#  ifdef _S_ISSOCK
#    define S_ISSOCK(m) _S_ISSOCK(m)
#  else
#    ifdef _S_IFSOCK
#      define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
#    else
#      ifdef S_IFSOCK
#	 define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
#      endif
#    endif
#  endif
#endif

#ifdef S_ISSOCK
    struct stat st;

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

#endif
    return Qfalse;
}

.split(file_name) ⇒ Array

Splits the given string into a directory and a file component and returns them in a two-element array. See also .dirname and .basename.

File.split("/home/gumby/.profile")   #=> ["/home/gumby", ".profile"]
[ GitHub ]

  
# File 'file.c', line 4569

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

.stat(file_name) ⇒ stat

Returns a ::File::Stat object for the named file (see ::File::Stat).

File.stat("testfile").mtime   #=> Tue Apr 08 12:58:04 CDT 2003
[ GitHub ]

  
# File 'file.c', line 1148

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

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

.sticky?(file_name) ⇒ Boolean

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

[ GitHub ]

  
# File 'file.c', line 1986

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

.symlink?(file_name) ⇒ Boolean

Returns true if the named file is a symbolic link.

[ GitHub ]

  
# File 'file.c', line 1495

static VALUE
rb_file_symlink_p(VALUE obj, VALUE fname)
{
#ifndef S_ISLNK
#  ifdef _S_ISLNK
#    define S_ISLNK(m) _S_ISLNK(m)
#  else
#    ifdef _S_IFLNK
#      define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)
#    else
#      ifdef S_IFLNK
#	 define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
#      endif
#    endif
#  endif
#endif

#ifdef S_ISLNK
    struct stat st;

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

    return Qfalse;
}

.truncate(file_name, integer) ⇒ 0

Truncates the file file_name to be at most integer bytes long. Not available on all platforms.

f = File.new("out", "w")
f.write("1234567890")     #=> 10
f.close                   #=> nil
File.truncate("out", 5)   #=> 0
File.size("out")          #=> 5
[ GitHub ]

  
# File 'file.c', line 4721

static VALUE
rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
{
    struct truncate_arg ta;
    int r;

    ta.pos = NUM2POS(len);
    FilePathValue(path);
    path = rb_str_encode_ospath(path);
    ta.path = StringValueCStr(path);

    r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_truncate, &ta,
						RUBY_UBF_IO, NULL);
    if (r < 0)
	rb_sys_fail_path(path);
    return INT2FIX(0);
#undef NUM2POS
}

.umaskInteger .umask(integer) ⇒ Integer

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

File.umask(0006)   #=> 18
File.umask         #=> 6
[ GitHub ]

  
# File 'file.c', line 3060

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

    if (argc == 0) {
	omask = umask(0);
	umask(omask);
    }
    else if (argc == 1) {
	omask = umask(NUM2MODET(argv[0]));
    }
    else {
	rb_check_arity(argc, 0, 1);
    }
    return MODET2NUM(omask);
}

.utime(atime, mtime, file_name,...) ⇒ Integer

Sets the access and modification times of each named file to the first two arguments. If a file is a symlink, this method acts upon its referent rather than the link itself; for the inverse behavior see .lutime. Returns the number of file names in the argument list.

[ GitHub ]

  
# File 'file.c', line 2762

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

.world_readable?(file_name) ⇒ Integer?

If file_name is readable by others, returns an integer representing the file permission bits of file_name. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

file_name can be an ::IO object.

File.world_readable?("/etc/passwd")           #=> 420
m = File.world_readable?("/etc/passwd")
sprintf("%o", m)                              #=> "644"
[ GitHub ]

  
# File 'file.c', line 1709

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

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

.world_writable?(file_name) ⇒ Integer?

If file_name is writable by others, returns an integer representing the file permission bits of file_name. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

file_name can be an ::IO object.

File.world_writable?("/tmp")                  #=> 511
m = File.world_writable?("/tmp")
sprintf("%o", m)                              #=> "777"
[ GitHub ]

  
# File 'file.c', line 1769

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

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

.writable?(file_name) ⇒ Boolean

Returns true if the named file is writable by the effective user and group id of this process. See eaccess(3).

[ GitHub ]

  
# File 'file.c', line 1731

static VALUE
rb_file_writable_p(VALUE obj, VALUE fname)
{
    if (rb_eaccess(fname, W_OK) < 0) return Qfalse;
    return Qtrue;
}

.writable_real?(file_name) ⇒ Boolean

Returns true if the named file is writable by the real user and group id of this process. See access(3)

[ GitHub ]

  
# File 'file.c', line 1746

static VALUE
rb_file_writable_real_p(VALUE obj, VALUE fname)
{
    if (rb_access(fname, W_OK) < 0) return Qfalse;
    return Qtrue;
}

.zero?(file_name) ⇒ Boolean

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

file_name can be an ::IO object.

[ GitHub ]

  
# File 'file.c', line 1849

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

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

Instance Method Details

#atimeTime

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

File.new("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969
[ GitHub ]

  
# File 'file.c', line 2160

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

#birthtimeTime

Returns the birth time for file.

File.new("testfile").birthtime   #=> Wed Apr 09 08:53:14 CDT 2003

If the platform doesn't have birthtime, raises ::NotImplementedError.

[ GitHub ]

  
# File 'file.c', line 2320

static VALUE
rb_file_birthtime(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_birthtime(&st);
}

#chmod(mode_int) ⇒ 0

Changes permission bits on file to the bit pattern represented by mode_int. Actual effects are platform dependent; on Unix systems, see chmod(2) for details. Follows symbolic links. Also see File#lchmod.

f = File.new("out", "w");
f.chmod(0644)   #=> 0
[ GitHub ]

  
# File 'file.c', line 2405

static VALUE
rb_file_chmod(VALUE obj, VALUE vmode)
{
    rb_io_t *fptr;
    int mode;
#if !defined HAVE_FCHMOD || !HAVE_FCHMOD
    VALUE path;
#endif

    mode = NUM2INT(vmode);

    GetOpenFile(obj, fptr);
#ifdef HAVE_FCHMOD
    if (fchmod(fptr->fd, mode) == -1) {
	if (HAVE_FCHMOD || errno != ENOSYS)
	    rb_sys_fail_path(fptr->pathv);
    }
    else {
	if (!HAVE_FCHMOD) return INT2FIX(0);
    }
#endif
#if !defined HAVE_FCHMOD || !HAVE_FCHMOD
    if (NIL_P(fptr->pathv)) return Qnil;
    path = rb_str_encode_ospath(fptr->pathv);
    if (chmod(RSTRING_PTR(path), mode) == -1)
	rb_sys_fail_path(fptr->pathv);
#endif

    return INT2FIX(0);
}

#chown(owner_int, group_int) ⇒ 0

Changes the owner and group of file to the given numeric owner and group id's. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file's group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Follows symbolic links. See also File#lchown.

File.new("testfile").chown(502, 1000)
[ GitHub ]

  
# File 'file.c', line 2539

static VALUE
rb_file_chown(VALUE obj, VALUE owner, VALUE group)
{
    rb_io_t *fptr;
    rb_uid_t o;
    rb_gid_t g;
#ifndef HAVE_FCHOWN
    VALUE path;
#endif

    o = to_uid(owner);
    g = to_gid(group);
    GetOpenFile(obj, fptr);
#ifndef HAVE_FCHOWN
    if (NIL_P(fptr->pathv)) return Qnil;
    path = rb_str_encode_ospath(fptr->pathv);
    if (chown(RSTRING_PTR(path), o, g) == -1)
	rb_sys_fail_path(fptr->pathv);
#else
    if (fchown(fptr->fd, o, g) == -1)
	rb_sys_fail_path(fptr->pathv);
#endif

    return INT2FIX(0);
}

#ctimeTime

Returns the change time for file (that is, the time directory information about the file was changed, not the file itself).

Note that on Windows (NTFS), returns creation time (birth time).

File.new("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003
[ GitHub ]

  
# File 'file.c', line 2263

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, false

Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms.

Locking constants (in class File):

LOCK_EX   | Exclusive lock. Only one process may hold an
          | exclusive lock for a given file at a time.
----------+------------------------------------------------
LOCK_NB   | Don't block when locking. May be combined
          | with other lock options using logical or.
----------+------------------------------------------------
LOCK_SH   | Shared lock. Multiple processes may each hold a
          | shared lock for a given file at the same time.
----------+------------------------------------------------
LOCK_UN   | Unlock.

Example:

# update a counter using write lock
# don't use "w" because it truncates the file before lock.
File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
  f.flock(File::LOCK_EX)
  value = f.read.to_i + 1
  f.rewind
  f.write("#{value}\n")
  f.flush
  f.truncate(f.pos)
}

# read the counter using read lock
File.open("counter", "r") {|f|
  f.flock(File::LOCK_SH)
  p f.read
}
[ GitHub ]

  
# File 'file.c', line 4882

static VALUE
rb_file_flock(VALUE obj, VALUE operation)
{
    rb_io_t *fptr;
    int op[2], op1;
    struct timeval time;

    op[1] = op1 = NUM2INT(operation);
    GetOpenFile(obj, fptr);
    op[0] = fptr->fd;

    if (fptr->mode & FMODE_WRITABLE) {
	rb_io_flush_raw(obj, 0);
    }
    while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) {
	int e = errno;
	switch (e) {
	  case EAGAIN:
	  case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
	  case EWOULDBLOCK:
#endif
	    if (op1 & LOCK_NB) return Qfalse;

	    time.tv_sec = 0;
	    time.tv_usec = 100 * 1000;	/* 0.1 sec */
	    rb_thread_wait_for(time);
	    rb_io_check_closed(fptr);
	    continue;

	  case EINTR:
#if defined(ERESTART)
	  case ERESTART:
#endif
	    break;

	  default:
	    rb_syserr_fail_path(e, fptr->pathv);
	}
    }
    return INT2FIX(0);
}

#lstatstat

Same as IO#stat, but does not follow the last symbolic link. Instead, reports on the link itself.

File.symlink("testfile", "link2test")   #=> 0
File.stat("testfile").size              #=> 66
f = File.new("link2test")
f.lstat.size                            #=> 8
f.stat.size                             #=> 66
[ GitHub ]

  
# File 'file.c', line 1255

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
}

#mtimeTime

Returns the modification time for file.

File.new("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003
[ GitHub ]

  
# File 'file.c', line 2208

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

#pathFile #to_pathFile
Also known as: #to_path

Returns the pathname used to create file as a string. Does not normalize the name.

The pathname may not point to the file corresponding to file. For instance, the pathname becomes void when the file has been moved or deleted.

This method raises ::IOError for a file created using Constants::TMPFILE because they don't have a pathname.

File.new("testfile").path               #=> "testfile"
File.new("/tmp/../tmp/xxx", "w").path   #=> "/tmp/../tmp/xxx"
[ GitHub ]

  
# File 'file.c', line 441

static VALUE
rb_file_path(VALUE obj)
{
    rb_io_t *fptr;

    fptr = RFILE(rb_io_taint_check(obj))->fptr;
    rb_io_check_initialized(fptr);

    if (NIL_P(fptr->pathv)) {
        rb_raise(rb_eIOError, "File is unnamed (TMPFILE?)");
    }

    return rb_obj_taint(rb_str_dup(fptr->pathv));
}

#sizeInteger

Returns the size of file in bytes.

File.new("testfile").size   #=> 66
[ GitHub ]

  
# File 'file.c', line 2346

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

    GetOpenFile(obj, fptr);
    if (fptr->mode & FMODE_WRITABLE) {
	rb_io_flush_raw(obj, 0);
    }
    if (fstat(fptr->fd, &st) == -1) {
	rb_sys_fail_path(fptr->pathv);
    }
    return OFFT2NUM(st.st_size);
}

#pathFile #to_pathFile

Alias for #path.

#truncate(integer) ⇒ 0

Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.

f = File.new("out", "w")
f.syswrite("1234567890")   #=> 10
f.truncate(5)              #=> 0
f.close()                  #=> nil
File.size("out")           #=> 5
[ GitHub ]

  
# File 'file.c', line 4781

static VALUE
rb_file_truncate(VALUE obj, VALUE len)
{
    rb_io_t *fptr;
    struct ftruncate_arg fa;

    fa.pos = NUM2POS(len);
    GetOpenFile(obj, fptr);
    if (!(fptr->mode & FMODE_WRITABLE)) {
	rb_raise(rb_eIOError, "not opened for writing");
    }
    rb_io_flush_raw(obj, 0);
    fa.fd = fptr->fd;
    if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) {
	rb_sys_fail_path(fptr->pathv);
    }
    return INT2FIX(0);
#undef NUM2POS
}