Class File
In: file.c
lib/ftools.rb
lib/pp.rb

ftools.rb: Extra tools for the File class

Author:WATANABE, Hirofumi
Documentation:Zachary Landau

This library can be distributed under the terms of the Ruby license. You can freely distribute/modify this library.

It is included in the Ruby standard library.

Description

ftools adds several (class, not instance) methods to the File class, for copying, moving, deleting, installing, and comparing files, as well as creating a directory path. See the File class for details.

FileUtils contains all or nearly all the same functionality and more, and is a recommended option over ftools

When you

  require 'ftools'

then the File class aquires some utility methods for copying, moving, and deleting files, and more.

See the method descriptions below, and consider using FileUtils as it is more comprehensive.

Methods

atime   atime   basename   blockdev?   catname   chardev?   chmod   chmod   chmod   chown   chown   compare   copy   ctime   ctime   delete   directory?   dirname   executable?   executable_real?   exist?   exists?   expand_path   extname   file?   flock   fnmatch   fnmatch?   ftype   grpowned?   identical?   install   join   lchmod   lchown   link   lstat   lstat   makedirs   move   mtime   mtime   new   o_chmod   owned?   path   pipe?   readable?   readable_real?   readlink   rename   safe_unlink   setgid?   setuid?   size   size?   socket?   split   stat   sticky?   symlink   symlink?   syscopy   truncate   truncate   umask   unlink   utime   writable?   writable_real?   zero?  

Classes and Modules

Module File::Constants
Class File::Stat

Constants

Separator = separator
SEPARATOR = separator
ALT_SEPARATOR = rb_obj_freeze(rb_str_new2("\\"))
ALT_SEPARATOR = Qnil
PATH_SEPARATOR = rb_obj_freeze(rb_str_new2(PATH_SEP))
BUFSIZE = 8 * 1024

External Aliases

copy -> cp
move -> mv
compare -> cmp
safe_unlink -> rm_f
makedirs -> mkpath

Public Class methods

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

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

[Source]

/*
 *  call-seq:
 *     File.atime(file_name)  =>  time
 *  
 *  Returns the last access time for the named file as a Time object).
 *     
 *     File.atime("testfile")   #=> Wed Apr 09 08:51:48 CDT 2003
 *     
 */

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

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(StringValueCStr(fname));
    return rb_time_new(st.st_atime, 0);
}

Returns the last component of the filename given in file_name, which must be formed using forward slashes (``/’’) regardless of the separator used on the local file system. If suffix is given and present at the end of file_name, it is removed.

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

[Source]

/*
 *  call-seq:
 *     File.basename(file_name [, suffix] ) -> base_name
 *  
 *  Returns the last component of the filename given in <i>file_name</i>,
 *  which must be formed using forward slashes (``<code>/</code>'')
 *  regardless of the separator used on the local file system. If
 *  <i>suffix</i> is given and present at the end of <i>file_name</i>,
 *  it is removed.
 *     
 *     File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
 *     File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"
 */

static VALUE
rb_file_s_basename(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, fext, basename;
    const char *name, *p;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
    const char *root;
#endif
    int f, n;

    if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
        StringValue(fext);
    }
    StringValue(fname);
    if (RSTRING(fname)->len == 0 || !*(name = RSTRING(fname)->ptr))
        return fname;
    name = skipprefix(name);
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
    root = name;
#endif
    while (isdirsep(*name))
        name++;
    if (!*name) {
        p = name - 1;
        f = 1;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
        if (name != root) {
            /* has slashes */
        }
#ifdef DOSISH_DRIVE_LETTER
        else if (*p == ':') {
            p++;
            f = 0;
        }
#endif
#ifdef DOSISH_UNC
        else {
            p = "/";
        }
#endif
#endif
    }
    else {
        if (!(p = strrdirsep(name))) {
            p = name;
        }
        else {
            while (isdirsep(*p)) p++; /* skip last / */
        }
#if USE_NTFS
        n = ntfs_tail(p) - p;
#else
        n = chompdirsep(p) - p;
#endif
        if (NIL_P(fext) || !(f = rmext(p, n, StringValueCStr(fext)))) {
            f = n;
        }
        if (f == RSTRING_LEN(fname)) return fname;
    }
    basename = rb_str_new(p, f);
    OBJ_INFECT(basename, fname);
    return basename;
}

Returns true if the named file is a block device.

[Source]

/*
 * call-seq:
 *   File.blockdev?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a block device.
 */

static VALUE
test_b(obj, fname)
    VALUE obj, 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;
}

If to is a valid directory, from will be appended to to, adding and escaping backslashes as necessary. Otherwise, to will be returned. Useful for appending from to to only if the filename was not specified in to.

[Source]

    # File lib/ftools.rb, line 44
44:   def catname(from, to)
45:     if directory? to
46:       join to.sub(%r([/\\]$), ''), basename(from)
47:     else
48:       to
49:     end
50:   end

Returns true if the named file is a character device.

[Source]

/*
 * call-seq:
 *   File.chardev?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a character device.
 */
static VALUE
test_c(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISCHR
#   define S_ISCHR(m) ((m & S_IFMT) == S_IFCHR)
#endif

    struct stat st;

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

    return Qfalse;
}

Changes 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

[Source]

/*
 *  call-seq:
 *     File.chmod(mode_int, file_name, ... ) -> integer
 *  
 *  Changes permission bits on the named file(s) to the bit pattern
 *  represented by <i>mode_int</i>. Actual effects are operating system
 *  dependent (see the beginning of this section). On Unix systems, see
 *  <code>chmod(2)</code> for details. Returns the number of files
 *  processed.
 *     
 *     File.chmod(0644, "testfile", "out")   #=> 2
 */

static VALUE
rb_file_s_chmod(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE vmode;
    VALUE rest;
    int mode;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "1*", &vmode, &rest);
    mode = NUM2INT(vmode);

    n = apply2files(chmod_internal, rest, &mode);
    return LONG2FIX(n);
}

Changes permission bits on files to the bit pattern represented by mode. If the last parameter isn‘t a String, verbose mode will be enabled.

  File.chmod 0755, 'somecommand'
  File.chmod 0644, 'my.rb', 'your.rb', true

[Source]

     # File lib/ftools.rb, line 237
237:   def chmod(mode, *files)
238:     verbose = if files[-1].is_a? String then false else files.pop end
239:     $stderr.printf "chmod %04o %s\n", mode, files.join(" ") if verbose
240:     o_chmod mode, *files
241:   end

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

[Source]

/*
 *  call-seq:
 *     File.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 <code>nil</code> 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(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE o, g, rest;
    struct chown_args arg;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "2*", &o, &g, &rest);
    if (NIL_P(o)) {
        arg.owner = -1;
    }
    else {
        arg.owner = NUM2INT(o);
    }
    if (NIL_P(g)) {
        arg.group = -1;
    }
    else {
        arg.group = NUM2INT(g);
    }

    n = apply2files(chown_internal, rest, &arg);
    return LONG2FIX(n);
}

Returns true if and only if the contents of files from and to are identical. If verbose is true, from <=> to is printed.

[Source]

     # File lib/ftools.rb, line 130
130:   def compare(from, to, verbose = false)
131:     $stderr.print from, " <=> ", to, "\n" if verbose
132: 
133:     return false if stat(from).size != stat(to).size
134: 
135:     from = open(from, "rb")
136:     to = open(to, "rb")
137: 
138:     ret = false
139:     fr = tr = ''
140: 
141:     begin
142:       while fr == tr
143:         fr = from.read(BUFSIZE)
144:         if fr
145:           tr = to.read(fr.size)
146:         else
147:           ret = to.read(BUFSIZE)
148:           ret = !ret || ret.length == 0
149:           break
150:         end
151:       end
152:     rescue
153:       ret = false
154:     ensure
155:       to.close
156:       from.close
157:     end
158:     ret
159:   end

Copies a file from to to using syscopy. If to is a directory, copies from to to/from. If verbose is true, from -> to is printed.

[Source]

    # File lib/ftools.rb, line 87
87:   def copy(from, to, verbose = false)
88:     $stderr.print from, " -> ", catname(from, to), "\n" if verbose
89:     syscopy from, to
90:   end

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

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

[Source]

/*
 *  call-seq:
 *     File.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.ctime("testfile")   #=> Wed Apr 09 08:53:13 CDT 2003
 *     
 */

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

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(RSTRING(fname)->ptr);
    return rb_time_new(st.st_ctime, 0);
}

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir.

[Source]

/*
 *  call-seq:
 *     File.delete(file_name, ...)  => integer
 *     File.unlink(file_name, ...)  => integer
 *  
 *  Deletes the named files, returning the number of names
 *  passed as arguments. Raises an exception on any error.
 *  See also <code>Dir::rmdir</code>.
 */

static VALUE
rb_file_s_unlink(klass, args)
    VALUE klass, args;
{
    long n;

    rb_secure(2);
    n = apply2files(unlink_internal, args, 0);
    return LONG2FIX(n);
}

Returns true if the named file is a directory, false otherwise.

   File.directory?(".")

[Source]

/*
 * call-seq:
 *   File.directory?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a directory,
 * <code>false</code> otherwise.
 *
 *    File.directory?(".")
 */

static VALUE
test_d(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISDIR
#   define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
#endif

    struct stat st;

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

Returns all components of the filename given in file_name except the last one. The filename must be formed using forward slashes (``/’’) regardless of the separator used on the local file system.

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

[Source]

/*
 *  call-seq:
 *     File.dirname(file_name ) -> dir_name
 *  
 *  Returns all components of the filename given in <i>file_name</i>
 *  except the last one. The filename must be formed using forward
 *  slashes (``<code>/</code>'') regardless of the separator used on the
 *  local file system.
 *     
 *     File.dirname("/home/gumby/work/ruby.rb")   #=> "/home/gumby/work"
 */

static VALUE
rb_file_s_dirname(klass, fname)
    VALUE klass, fname;
{
    const char *name, *root, *p;
    VALUE dirname;

    name = StringValueCStr(fname);
    root = skiproot(name);
#ifdef DOSISH_UNC
    if (root > name + 1 && isdirsep(*name))
        root = skipprefix(name = root - 2);
#else
    if (root > name + 1)
        name = root - 1;
#endif
    p = strrdirsep(root);
    if (!p) {
        p = root;
    }
    if (p == name)
        return rb_str_new2(".");
#ifdef DOSISH_DRIVE_LETTER
    if (has_drive_letter(name) && isdirsep(*(name + 2))) {
        const char *top = skiproot(name + 2);
        dirname = rb_str_new(name, 3);
        rb_str_cat(dirname, top, p - top);
    }
    else
#endif
    dirname = rb_str_new(name, p - name);
#ifdef DOSISH_DRIVE_LETTER
    if (has_drive_letter(name) && root == name + 2 && p - name == 2)
        rb_str_cat(dirname, ".", 1);
#endif
    OBJ_INFECT(dirname, fname);
    return dirname;
}

Returns true if the named file is executable by the effective user id of this process.

[Source]

/*
 * call-seq:
 *    File.executable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is executable by the effective
 * user id of this process.
 */

static VALUE
test_x(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), X_OK) < 0) return Qfalse;
    return Qtrue;
}

Returns true if the named file is executable by the real user id of this process.

[Source]

/*
 * call-seq:
 *    File.executable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is executable by the real
 * user id of this process.
 */

static VALUE
test_X(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), X_OK) < 0) return Qfalse;
    return Qtrue;
}

Return true if the named file exists.

[Source]

/*
 * call-seq:
 *    File.exist?(file_name)    =>  true or false
 *    File.exists?(file_name)   =>  true or false    (obsolete)
 *
 * Return <code>true</code> if the named file exists.
 */

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

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

Return true if the named file exists.

[Source]

/*
 * call-seq:
 *    File.exist?(file_name)    =>  true or false
 *    File.exists?(file_name)   =>  true or false    (obsolete)
 *
 * Return <code>true</code> if the named file exists.
 */

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

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

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"
   File.expand_path("../../bin", "/tmp/x")   #=> "/bin"

[Source]

/*
 *  call-seq:
 *     File.expand_path(file_name [, dir_string] ) -> abs_file_name
 *  
 *  Converts a pathname to an absolute pathname. Relative paths are
 *  referenced from the current working directory of the process unless
 *  <i>dir_string</i> is given, in which case it will be used as the
 *  starting point. The given pathname may start with a
 *  ``<code>~</code>'', which expands to the process owner's home
 *  directory (the environment variable <code>HOME</code> must be set
 *  correctly). ``<code>~</code><i>user</i>'' expands to the named
 *  user's home directory.
 *     
 *     File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"
 *     File.expand_path("../../bin", "/tmp/x")   #=> "/bin"
 */

VALUE
rb_file_s_expand_path(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE fname, dname;

    if (argc == 1) {
        return rb_file_expand_path(argv[0], Qnil);
    }
    rb_scan_args(argc, argv, "11", &fname, &dname);

    return rb_file_expand_path(fname, dname);
}

Returns the extension (the portion of file name in path after the period).

   File.extname("test.rb")         #=> ".rb"
   File.extname("a/b/d/test.rb")   #=> ".rb"
   File.extname("test")            #=> ""
   File.extname(".profile")        #=> ""

[Source]

/*
 *  call-seq:
 *     File.extname(path) -> string
 *  
 *  Returns the extension (the portion of file name in <i>path</i>
 *  after the period).
 *     
 *     File.extname("test.rb")         #=> ".rb"
 *     File.extname("a/b/d/test.rb")   #=> ".rb"
 *     File.extname("test")            #=> ""
 *     File.extname(".profile")        #=> ""
 *     
 */

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

    name = StringValueCStr(fname);
    p = strrdirsep(name);       /* get the last path component */
    if (!p)
        p = name;
    else
        name = ++p;

    e = 0;
    while (*p) {
        if (*p == '.' || istrailinggabage(*p)) {
#if USE_NTFS
            const char *last = p++, *dot = last;
            while (istrailinggabage(*p)) {
                if (*p == '.') dot = p;
                p++;
            }
            if (!*p || *p == ':') {
                p = last;
                break;
            }
            if (*last == '.') e = dot;
            continue;
#else
            e = p;       /* get the last dot of the last component */
#endif
        }
#if USE_NTFS
        else if (*p == ':') {
            break;
        }
#endif
        else if (isdirsep(*p))
            break;
        p = CharNext(p);
    }
    if (!e || e == name || e+1 == p)    /* no dot, or the only dot is first or end? */
        return rb_str_new(0, 0);
    extname = rb_str_new(e, p - e);     /* keep the dot, too! */
    OBJ_INFECT(extname, fname);
    return extname;
}

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

[Source]

/*
 * call-seq:
 *    File.file?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and is a
 * regular file.
 */

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

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

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. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp.
**: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]).
<code></code>:Escapes the next metacharacter.

flags is a bitwise OR of the FNM_xxx parameters. The same glob pattern and flags are used by Dir::glob.

   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

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

[Source]

/*
 *  call-seq:
 *     File.fnmatch( pattern, path, [flags] ) => (true or false)
 *     File.fnmatch?( pattern, path, [flags] ) => (true or false)
 *
 *  Returns true if <i>path</i> matches against <i>pattern</i> The
 *  pattern is not a regular expression; instead it follows rules
 *  similar to shell filename globbing. It may contain the following
 *  metacharacters:
 *
 *  <code>*</code>::        Matches any file. Can be restricted by
 *                          other values in the glob. <code>*</code>
 *                          will match all files; <code>c*</code> will
 *                          match all files beginning with
 *                          <code>c</code>; <code>*c</code> will match
 *                          all files ending with <code>c</code>; and
 *                          <code>*c*</code> will match all files that
 *                          have <code>c</code> in them (including at
 *                          the beginning or end). Equivalent to
 *                          <code>/ .* /x</code> in regexp.
 *  <code>**</code>::       Matches directories recursively or files
 *                          expansively.
 *  <code>?</code>::        Matches any one character. Equivalent to
 *                          <code>/.{1}/</code> in regexp.
 *  <code>[set]</code>::    Matches any one character in +set+.
 *                          Behaves exactly like character sets in
 *                          Regexp, including set negation
 *                          (<code>[^a-z]</code>).
 *  <code>\</code>::        Escapes the next metacharacter.
 *
 *  <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
 *  parameters. The same glob pattern and flags are used by
 *  <code>Dir::glob</code>.
 *
 *     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
 *
 *     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_NOESACPE 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
 */
static VALUE
file_s_fnmatch(argc, argv, obj)
    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;

    StringValue(pattern);
    StringValue(path);

    if (fnmatch(RSTRING(pattern)->ptr, RSTRING(path)->ptr, flags) == 0)
        return Qtrue;

    return Qfalse;
}

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. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp.
**: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]).
<code></code>:Escapes the next metacharacter.

flags is a bitwise OR of the FNM_xxx parameters. The same glob pattern and flags are used by Dir::glob.

   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

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

[Source]

/*
 *  call-seq:
 *     File.fnmatch( pattern, path, [flags] ) => (true or false)
 *     File.fnmatch?( pattern, path, [flags] ) => (true or false)
 *
 *  Returns true if <i>path</i> matches against <i>pattern</i> The
 *  pattern is not a regular expression; instead it follows rules
 *  similar to shell filename globbing. It may contain the following
 *  metacharacters:
 *
 *  <code>*</code>::        Matches any file. Can be restricted by
 *                          other values in the glob. <code>*</code>
 *                          will match all files; <code>c*</code> will
 *                          match all files beginning with
 *                          <code>c</code>; <code>*c</code> will match
 *                          all files ending with <code>c</code>; and
 *                          <code>*c*</code> will match all files that
 *                          have <code>c</code> in them (including at
 *                          the beginning or end). Equivalent to
 *                          <code>/ .* /x</code> in regexp.
 *  <code>**</code>::       Matches directories recursively or files
 *                          expansively.
 *  <code>?</code>::        Matches any one character. Equivalent to
 *                          <code>/.{1}/</code> in regexp.
 *  <code>[set]</code>::    Matches any one character in +set+.
 *                          Behaves exactly like character sets in
 *                          Regexp, including set negation
 *                          (<code>[^a-z]</code>).
 *  <code>\</code>::        Escapes the next metacharacter.
 *
 *  <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
 *  parameters. The same glob pattern and flags are used by
 *  <code>Dir::glob</code>.
 *
 *     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
 *
 *     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_NOESACPE 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
 */
static VALUE
file_s_fnmatch(argc, argv, obj)
    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;

    StringValue(pattern);
    StringValue(path);

    if (fnmatch(RSTRING(pattern)->ptr, RSTRING(path)->ptr, flags) == 0)
        return Qtrue;

    return Qfalse;
}

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"

[Source]

/*
 *  call-seq:
 *     File.ftype(file_name)   => string
 *  
 *  Identifies the type of the named file; the return string is one of
 *  ``<code>file</code>'', ``<code>directory</code>'',
 *  ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
 *  ``<code>fifo</code>'', ``<code>link</code>'',
 *  ``<code>socket</code>'', or ``<code>unknown</code>''.
 *     
 *     File.ftype("testfile")            #=> "file"
 *     File.ftype("/dev/tty")            #=> "characterSpecial"
 *     File.ftype("/tmp/.X11-unix/X0")   #=> "socket"
 */

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

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) == -1) {
        rb_sys_fail(RSTRING(fname)->ptr);
    }

    return rb_file_ftype(&st);
}

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.

[Source]

/*
 * call-seq:
 *    File.grpowned?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and the
 * effective group id of the calling process is the owner of
 * the file. Returns <code>false</code> on Windows.
 */

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

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

Returns true if the named files are identical.

    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

[Source]

/*
 * call-seq:
 *   File.identical?(file_1, file_2)   =>  true or false
 *
 * Returns <code>true</code> if the named files are identical.
 *
 *     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
 */

static VALUE
test_identical(obj, fname1, fname2)
    VALUE obj, fname1, fname2;
{
#ifndef DOSISH
    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;
#else
#ifdef _WIN32
    BY_HANDLE_FILE_INFORMATION st1, st2;
    HANDLE f1 = 0, f2 = 0;
#endif

    rb_secure(2);
#ifdef _WIN32
    f1 = w32_io_info(&fname1, &st1);
    if (f1 == INVALID_HANDLE_VALUE) return Qfalse;
    f2 = w32_io_info(&fname2, &st2);
    if (f1) CloseHandle(f1);
    if (f2 == INVALID_HANDLE_VALUE) return Qfalse;
    if (f2) CloseHandle(f2);

    if (st1.dwVolumeSerialNumber == st2.dwVolumeSerialNumber &&
        st1.nFileIndexHigh == st2.nFileIndexHigh &&
        st1.nFileIndexLow == st2.nFileIndexLow)
        return Qtrue;
    if (!f1 || !f2) return Qfalse;
    if (rb_w32_iswin95()) return Qfalse;
#else
    SafeStringValue(fname1);
    fname1 = rb_str_new4(fname1);
    SafeStringValue(fname2);
    if (access(RSTRING(fname1)->ptr, 0)) return Qfalse;
    if (access(RSTRING(fname2)->ptr, 0)) return Qfalse;
#endif
    fname1 = rb_file_expand_path(fname1, Qnil);
    fname2 = rb_file_expand_path(fname2, Qnil);
    if (RSTRING(fname1)->len != RSTRING(fname2)->len) return Qfalse;
    if (rb_memcicmp(RSTRING(fname1)->ptr, RSTRING(fname2)->ptr, RSTRING(fname1)->len))
        return Qfalse;
#endif
    return Qtrue;
}

If src is not the same as dest, copies it and changes the permission mode to mode. If dest is a directory, destination is dest/src. If mode is not set, default is used. If verbose is set to true, the name of each file copied will be printed.

[Source]

     # File lib/ftools.rb, line 250
250:   def install(from, to, mode = nil, verbose = false)
251:     to = catname(from, to)
252:     unless exist? to and cmp from, to
253:       safe_unlink to if exist? to
254:       cp from, to, verbose
255:       chmod mode, to, verbose if mode
256:     end
257:   end

Returns a new string formed by joining the strings using File::SEPARATOR.

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

[Source]

/*
 *  call-seq:
 *     File.join(string, ...) -> path
 *  
 *  Returns a new string formed by joining the strings using
 *  <code>File::SEPARATOR</code>.
 *     
 *     File.join("usr", "mail", "gumby")   #=> "usr/mail/gumby"
 *     
 */

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

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.

[Source]

/*
 *  call-seq:
 *     File.lchmod(mode_int, file_name, ...)  => integer
 *  
 *  Equivalent to <code>File::chmod</code>, 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(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE vmode;
    VALUE rest;
    long mode, n;

    rb_secure(2);
    rb_scan_args(argc, argv, "1*", &vmode, &rest);
    mode = NUM2INT(vmode);

    n = apply2files(lchmod_internal, rest, (void *)(long)mode);
    return LONG2FIX(n);
}

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.

[Source]

/*
 *  call-seq:
 *     file.lchown(owner_int, group_int, file_name,..) => integer
 *  
 *  Equivalent to <code>File::chown</code>, 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(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE o, g, rest;
    struct chown_args arg;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "2*", &o, &g, &rest);
    if (NIL_P(o)) {
        arg.owner = -1;
    }
    else {
        arg.owner = NUM2INT(o);
    }
    if (NIL_P(g)) {
        arg.group = -1;
    }
    else {
        arg.group = NUM2INT(g);
    }

    n = apply2files(lchown_internal, rest, &arg);
    return LONG2FIX(n);
}

Creates a new name for an existing file using a hard link. Will not overwrite new_name if it already exists (raising a subclass of SystemCallError). Not available on all platforms.

   File.link("testfile", ".testfile")   #=> 0
   IO.readlines(".testfile")[0]         #=> "This is line one\n"

[Source]

/*
 *  call-seq:
 *     File.link(old_name, new_name)    => 0
 *  
 *  Creates a new name for an existing file using a hard link. Will not
 *  overwrite <i>new_name</i> if it already exists (raising a subclass
 *  of <code>SystemCallError</code>). Not available on all platforms.
 *     
 *     File.link("testfile", ".testfile")   #=> 0
 *     IO.readlines(".testfile")[0]         #=> "This is line one\n"
 */

static VALUE
rb_file_s_link(klass, from, to)
    VALUE klass, from, to;
{
#ifdef HAVE_LINK
    SafeStringValue(from);
    SafeStringValue(to);

    if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
        sys_fail2(from, to);
    }
    return INT2FIX(0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}

Same as File::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

[Source]

/*
 *  call-seq:
 *     File.lstat(file_name)   => stat
 *  
 *  Same as <code>File::stat</code>, 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
 *     
 */

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

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) == -1) {
        rb_sys_fail(RSTRING(fname)->ptr);
    }
    return stat_new(&st);
#else
    return rb_file_s_stat(klass, fname);
#endif
}

Creates a directory and all its parent directories. For example,

    File.makedirs '/usr/lib/ruby'

causes the following directories to be made, if they do not exist.

    * /usr
    * /usr/lib
    * /usr/lib/ruby

You can pass several directories, each as a parameter. If the last parameter isn‘t a String, verbose mode will be enabled.

[Source]

     # File lib/ftools.rb, line 205
205:   def makedirs(*dirs)
206:     verbose = if dirs[-1].is_a? String then false else dirs.pop end
207:     mode = 0755
208:     for dir in dirs
209:       parent = dirname(dir)
210:       next if parent == dir or directory? dir
211:       makedirs parent unless directory? parent
212:       $stderr.print "mkdir ", dir, "\n" if verbose
213:       if basename(dir) != ""
214:         begin
215:           Dir.mkdir dir, mode
216:         rescue SystemCallError
217:           raise unless directory? dir
218:         end
219:       end
220:     end
221:   end

Moves a file from to to using syscopy. If to is a directory, copies from from to to/from. If verbose is true, from -> to is printed.

[Source]

     # File lib/ftools.rb, line 99
 99:   def move(from, to, verbose = false)
100:     to = catname(from, to)
101:     $stderr.print from, " -> ", to, "\n" if verbose
102: 
103:     if RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/ and file? to
104:       unlink to
105:     end
106:     fstat = stat(from)
107:     begin
108:       rename from, to
109:     rescue
110:       begin
111:         symlink readlink(from), to and unlink from
112:       rescue
113:         from_stat = stat(from)
114:         syscopy from, to and unlink from
115:         utime(from_stat.atime, from_stat.mtime, to)
116:         begin
117:           chown(fstat.uid, fstat.gid, to)
118:         rescue
119:         end
120:       end
121:     end
122:   end

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

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

[Source]

/*
 *  call-seq:
 *     File.mtime(file_name)  =>  time
 *  
 *  Returns the modification time for the named file as a Time object.
 *     
 *     File.mtime("testfile")   #=> Tue Apr 08 12:58:04 CDT 2003
 *     
 */

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

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(RSTRING(fname)->ptr);
    return rb_time_new(st.st_mtime, 0);
}

Opens the file named by filename according to mode (default is ``r’’) and returns a new File object. See the description of class IO for a description of mode. The file mode may optionally be specified as a Fixnum by or-ing together the flags (O_RDONLY etc, again described under IO). Optional permission bits may be given in perm. These mode and permission bits are platform dependent; on Unix systems, see open(2) for details.

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

[Source]

/*
 *  call-seq:
 *     File.new(filename, mode="r")            => file
 *     File.new(filename [, mode [, perm]])    => file
 *  

 *  Opens the file named by _filename_ according to
 *  _mode_ (default is ``r'') and returns a new
 *  <code>File</code> object. See the description of class +IO+ for
 *  a description of _mode_. The file mode may optionally be
 *  specified as a +Fixnum+ by _or_-ing together the
 *  flags (O_RDONLY etc, again described under +IO+). Optional
 *  permission bits may be given in _perm_. These mode and permission
 *  bits are platform dependent; on Unix systems, see
 *  <code>open(2)</code> for details.
 *
 *     f = File.new("testfile", "r")
 *     f = File.new("newfile",  "w+")
 *     f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
 */

static VALUE
rb_file_initialize(argc, argv, io)
    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_convert_type(argv[0], T_FIXNUM, "Fixnum", "to_int");

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

    return io;
}

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

[Source]

/*
 * call-seq:
 *    File.owned?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and the
 * effective used id of the calling process is the owner of
 * the file.
 */

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

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

Returns true if the named file is a pipe.

[Source]

/*
 * call-seq:
 *   File.pipe?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a pipe.
 */

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

    struct stat st;

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

#endif
    return Qfalse;
}

Returns true if the named file is readable by the effective user id of this process.

[Source]

/*
 * call-seq:
 *    File.readable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is readable by the effective
 * user id of this process.
 */

static VALUE
test_r(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), R_OK) < 0) return Qfalse;
    return Qtrue;
}

Returns true if the named file is readable by the real user id of this process.

[Source]

/*
 * call-seq:
 *    File.readable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is readable by the real
 * user id of this process.
 */

static VALUE
test_R(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), R_OK) < 0) return Qfalse;
    return Qtrue;
}

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

   File.symlink("testfile", "link2test")   #=> 0
   File.readlink("link2test")              #=> "testfile"

[Source]

/*
 *  call-seq:
 *     File.readlink(link_name) -> file_name
 *  
 *  Returns the name of the file referenced by the given link.
 *  Not available on all platforms.
 *     
 *     File.symlink("testfile", "link2test")   #=> 0
 *     File.readlink("link2test")              #=> "testfile"
 */

static VALUE
rb_file_s_readlink(klass, path)
    VALUE klass, path;
{
#ifdef HAVE_READLINK
    char *buf;
    int size = 100;
    int rv;
    VALUE v;

    SafeStringValue(path);
    buf = xmalloc(size);
    while ((rv = readlink(RSTRING(path)->ptr, buf, size)) == size
#ifdef _AIX
            || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
#endif
        ) {
        size *= 2;
        buf = xrealloc(buf, size);
    }
    if (rv < 0) {
        free(buf);
        rb_sys_fail(RSTRING(path)->ptr);
    }
    v = rb_tainted_str_new(buf, rv);
    free(buf);

    return v;
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}

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

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

[Source]

/*
 *  call-seq:
 *     File.rename(old_name, new_name)   => 0
 *  
 *  Renames the given file to the new name. Raises a
 *  <code>SystemCallError</code> if the file cannot be renamed.
 *     
 *     File.rename("afile", "afile.bak")   #=> 0
 */

static VALUE
rb_file_s_rename(klass, from, to)
    VALUE klass, from, to;
{
    const char *src, *dst;
    SafeStringValue(from);
    SafeStringValue(to);

    src = StringValueCStr(from);
    dst = StringValueCStr(to);
#if defined __CYGWIN__
    errno = 0;
#endif
    if (rename(src, dst) < 0) {
#if defined DOSISH && !defined _WIN32
        switch (errno) {
          case EEXIST:
#if defined (__EMX__)
          case EACCES:
#endif
            if (chmod(dst, 0666) == 0 &&
                unlink(dst) == 0 &&
                rename(src, dst) == 0)
                return INT2FIX(0);
        }
#endif
        sys_fail2(from, to);
    }

    return INT2FIX(0);
}

Removes a list of files. Each parameter should be the name of the file to delete. If the last parameter isn‘t a String, verbose mode will be enabled. Returns the number of files deleted.

[Source]

     # File lib/ftools.rb, line 168
168:   def safe_unlink(*files)
169:     verbose = if files[-1].is_a? String then false else files.pop end
170:     files.each do |file|
171:       begin
172:         unlink file
173:         $stderr.print "removing ", file, "\n" if verbose
174:       rescue Errno::EACCES # for Windows
175:         continue if symlink? file
176:         begin
177:           mode = stat(file).mode
178:           o_chmod mode | 0200, file
179:           unlink file
180:           $stderr.print "removing ", file, "\n" if verbose
181:         rescue
182:           o_chmod mode, file rescue nil
183:         end
184:       rescue
185:       end
186:     end
187:   end

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

[Source]

/*
 * call-seq:
 *   File.setgid?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the setgid bit set.
 */

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

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

[Source]

/*
 * call-seq:
 *   File.setuid?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the setuid bit set.
 */

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

Returns the size of file_name.

[Source]

/*
 * call-seq:
 *    File.size(file_name)   => integer
 *
 * Returns the size of <code>file_name</code>.
 */

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

    if (rb_stat(fname, &st) < 0)
        rb_sys_fail(StringValueCStr(fname));
    return OFFT2NUM(st.st_size);
}

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

[Source]

/*
 * call-seq:
 *    File.size?(file_name)   => Integer or nil
 *
 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
 * file otherwise.
 */

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

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

Returns true if the named file is a socket.

[Source]

/*
 * call-seq:
 *   File.socket?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a socket.
 */

static VALUE
test_S(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISSOCK
#  ifdef _S_ISSOCK
#    define S_ISSOCK(m) _S_ISSOCK(m)
#  elif defined __BORLANDC__
#    ifdef _S_IFSOCK
#      define S_ISSOCK(m) (((unsigned short)(m) & S_IFMT) == _S_IFSOCK)
#    else
#      ifdef S_IFSOCK
#        define S_ISSOCK(m) (((unsigned short)(m) & S_IFMT) == S_IFSOCK)
#      endif
#    endif
#  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;
}

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

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

[Source]

/*
 *  call-seq:
 *     File.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
 *  <code>File::dirname</code> and <code>File::basename</code>.
 *     
 *     File.split("/home/gumby/.profile")   #=> ["/home/gumby", ".profile"]
 */

static VALUE
rb_file_s_split(klass, path)
    VALUE klass, path;
{
    StringValue(path);          /* get rid of converting twice */
    return rb_assoc_new(rb_file_s_dirname(Qnil, path), rb_file_s_basename(1,&path));
}

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

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

[Source]

/*
 *  call-seq:
 *     File.stat(file_name)   =>  stat
 *  
 *  Returns a <code>File::Stat</code> object for the named file (see
 *  <code>File::Stat</code>).
 *     
 *     File.stat("testfile").mtime   #=> Tue Apr 08 12:58:04 CDT 2003
 *     
 */

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

    SafeStringValue(fname);
    if (rb_stat(fname, &st) < 0) {
        rb_sys_fail(StringValueCStr(fname));
    }
    return stat_new(&st);
}

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

[Source]

/*
 * call-seq:
 *   File.sticky?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file has the sticky bit set.
 */

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

Creates a symbolic link called new_name for the existing file old_name. Raises a NotImplemented exception on platforms that do not support symbolic links.

   File.symlink("testfile", "link2test")   #=> 0

[Source]

/*
 *  call-seq:
 *     File.symlink(old_name, new_name)   => 0
 *  
 *  Creates a symbolic link called <i>new_name</i> for the existing file
 *  <i>old_name</i>. Raises a <code>NotImplemented</code> exception on
 *  platforms that do not support symbolic links.
 *     
 *     File.symlink("testfile", "link2test")   #=> 0
 *     
 */

static VALUE
rb_file_s_symlink(klass, from, to)
    VALUE klass, from, to;
{
#ifdef HAVE_SYMLINK
    SafeStringValue(from);
    SafeStringValue(to);

    if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
        sys_fail2(from, to);
    }
    return INT2FIX(0);
#else
    rb_notimplement();
    return Qnil;                /* not reached */
#endif
}

Returns true if the named file is a symbolic link.

[Source]

/*
 * call-seq:
 *   File.symlink?(file_name)   =>  true or false
 *
 * Returns <code>true</code> if the named file is a symbolic link.
 */

static VALUE
test_l(obj, fname)
    VALUE obj, fname;
{
#ifndef S_ISLNK
#  ifdef _S_ISLNK
#    define S_ISLNK(m) _S_ISLNK(m)
#  elif defined __BORLANDC__
#    ifdef _S_IFLNK
#      define S_ISLNK(m) (((unsigned short)(m) & S_IFMT) == _S_IFLNK)
#    else
#      ifdef S_IFLNK
#        define S_ISLNK(m) (((unsigned short)(m) & S_IFMT) == S_IFLNK)
#      endif
#    endif
#  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;

    SafeStringValue(fname);
    if (lstat(StringValueCStr(fname), &st) < 0) return Qfalse;
    if (S_ISLNK(st.st_mode)) return Qtrue;
#endif

    return Qfalse;
}

Copies a file from to to. If to is a directory, copies from to to/from.

[Source]

    # File lib/ftools.rb, line 56
56:   def syscopy(from, to)
57:     to = catname(from, to)
58: 
59:     fmode = stat(from).mode
60:     tpath = to
61:     not_exist = !exist?(tpath)
62: 
63:     from = open(from, "rb")
64:     to = open(to, "wb")
65: 
66:     begin
67:       while true
68:         to.syswrite from.sysread(BUFSIZE)
69:       end
70:     rescue EOFError
71:       ret = true
72:     rescue
73:       ret = false
74:     ensure
75:       to.close
76:       from.close
77:     end
78:     chmod(fmode, tpath) if not_exist
79:     ret
80:   end

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

[Source]

/*
 *  call-seq:
 *     File.truncate(file_name, integer)  => 0
 *  
 *  Truncates the file <i>file_name</i> to be at most <i>integer</i>
 *  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
 *     
 */

static VALUE
rb_file_s_truncate(klass, path, len)
    VALUE klass, path, len;
{
    off_t pos;

    rb_secure(2);
    pos = NUM2OFFT(len);
    SafeStringValue(path);

#ifdef HAVE_TRUNCATE
    if (truncate(StringValueCStr(path), pos) < 0)
        rb_sys_fail(RSTRING(path)->ptr);
#else
# ifdef HAVE_CHSIZE
    {
        int tmpfd;

#  ifdef _WIN32
        if ((tmpfd = open(StringValueCStr(path), O_RDWR)) < 0) {
            rb_sys_fail(RSTRING(path)->ptr);
        }
#  else
        if ((tmpfd = open(StringValueCStr(path), 0)) < 0) {
            rb_sys_fail(RSTRING(path)->ptr);
        }
#  endif
        if (chsize(tmpfd, pos) < 0) {
            close(tmpfd);
            rb_sys_fail(RSTRING(path)->ptr);
        }
        close(tmpfd);
    }
# else
    rb_notimplement();
# endif
#endif
    return INT2FIX(0);
}

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

   File.umask(0006)   #=> 18
   File.umask         #=> 6

[Source]

/*
 *  call-seq:
 *     File.umask()          => integer
 *     File.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 <em>subtracted</em> from the
 *  default permissions, so a umask of <code>0222</code> would make a
 *  file read-only for everyone.
 *     
 *     File.umask(0006)   #=> 18
 *     File.umask         #=> 6
 */

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

    rb_secure(2);
    if (argc == 0) {
        omask = umask(0);
        umask(omask);
    }
    else if (argc == 1) {
        omask = umask(NUM2INT(argv[0]));
    }
    else {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    return INT2FIX(omask);
}

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir.

[Source]

/*
 *  call-seq:
 *     File.delete(file_name, ...)  => integer
 *     File.unlink(file_name, ...)  => integer
 *  
 *  Deletes the named files, returning the number of names
 *  passed as arguments. Raises an exception on any error.
 *  See also <code>Dir::rmdir</code>.
 */

static VALUE
rb_file_s_unlink(klass, args)
    VALUE klass, args;
{
    long n;

    rb_secure(2);
    n = apply2files(unlink_internal, args, 0);
    return LONG2FIX(n);
}

Sets the access and modification times of each named file to the first two arguments. Returns the number of file names in the argument list.

[Source]

/*
 * call-seq:
 *  File.utime(atime, mtime, file_name,...)   =>  integer
 *
 * Sets the access and modification times of each
 * named file to the first two arguments. Returns
 * the number of file names in the argument list.
 */

static VALUE
rb_file_s_utime(argc, argv)
    int argc;
    VALUE *argv;
{
    VALUE atime, mtime, rest;
    struct timeval tvs[2], *tvp = NULL;
    long n;

    rb_secure(2);
    rb_scan_args(argc, argv, "2*", &atime, &mtime, &rest);

    if (!NIL_P(atime) || !NIL_P(mtime)) {
        tvp = tvs;
        tvp[0] = rb_time_timeval(atime);
        tvp[1] = rb_time_timeval(mtime);
    }

    n = apply2files(utime_internal, rest, tvp);
    return LONG2FIX(n);
}

Returns true if the named file is writable by the effective user id of this process.

[Source]

/*
 * call-seq:
 *    File.writable?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is writable by the effective
 * user id of this process.
 */

static VALUE
test_w(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (eaccess(StringValueCStr(fname), W_OK) < 0) return Qfalse;
    return Qtrue;
}

Returns true if the named file is writable by the real user id of this process.

[Source]

/*
 * call-seq:
 *    File.writable_real?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file is writable by the real
 * user id of this process.
 */

static VALUE
test_W(obj, fname)
    VALUE obj, fname;
{
    SafeStringValue(fname);
    if (access(StringValueCStr(fname), W_OK) < 0) return Qfalse;
    return Qtrue;
}

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

[Source]

/*
 * call-seq:
 *    File.zero?(file_name)   => true or false
 *
 * Returns <code>true</code> if the named file exists and has
 * a zero size.
 */

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

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

Public Instance methods

Returns the last access time (a Time object)

 for <i>file</i>, or epoch if <i>file</i> has not been accessed.

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

[Source]

/*
 *  call-seq:
 *     file.atime    => time
 *  
 *  Returns the last access time (a <code>Time</code> object)
 *   for <i>file</i>, or epoch if <i>file</i> has not been accessed.
 *     
 *     File.new("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969
 *     
 */

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

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return rb_time_new(st.st_atime, 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

[Source]

/*
 *  call-seq:
 *     file.chmod(mode_int)   => 0
 *  
 *  Changes permission bits on <i>file</i> to the bit pattern
 *  represented by <i>mode_int</i>. Actual effects are platform
 *  dependent; on Unix systems, see <code>chmod(2)</code> for details.
 *  Follows symbolic links. Also see <code>File#lchmod</code>.
 *     
 *     f = File.new("out", "w");
 *     f.chmod(0644)   #=> 0
 */

static VALUE
rb_file_chmod(obj, vmode)
    VALUE obj, vmode;
{
    rb_io_t *fptr;
    int mode;

    rb_secure(2);
    mode = NUM2INT(vmode);

    GetOpenFile(obj, fptr);
#ifdef HAVE_FCHMOD
    if (fchmod(fileno(fptr->f), mode) == -1)
        rb_sys_fail(fptr->path);
#else
    if (!fptr->path) return Qnil;
    if (chmod(fptr->path, mode) == -1)
        rb_sys_fail(fptr->path);
#endif

    return INT2FIX(0);
}

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

   File.new("testfile").chown(502, 1000)

[Source]

/*
 *  call-seq:
 *     file.chown(owner_int, group_int )   => 0
 *  
 *  Changes the owner and group of <i>file</i> 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
 *  <code>nil</code> or -1 owner or group id is ignored. Follows
 *  symbolic links. See also <code>File#lchown</code>.
 *     
 *     File.new("testfile").chown(502, 1000)
 *     
 */

static VALUE
rb_file_chown(obj, owner, group)
    VALUE obj, owner, group;
{
    rb_io_t *fptr;
    int o, g;

    rb_secure(2);
    o = NIL_P(owner) ? -1 : NUM2INT(owner);
    g = NIL_P(group) ? -1 : NUM2INT(group);
    GetOpenFile(obj, fptr);
#if defined(DJGPP) || defined(__CYGWIN32__) || defined(_WIN32) || defined(__EMX__)
    if (!fptr->path) return Qnil;
    if (chown(fptr->path, o, g) == -1)
        rb_sys_fail(fptr->path);
#else
    if (fchown(fileno(fptr->f), o, g) == -1)
        rb_sys_fail(fptr->path);
#endif

    return INT2FIX(0);
}

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

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

[Source]

/*
 *  call-seq:
 *     file.ctime -> time
 *  
 *  Returns the change time for <i>file</i> (that is, the time directory
 *  information about the file was changed, not the file itself).
 *     
 *     File.new("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003
 *     
 */

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

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return rb_time_new(st.st_ctime, 0);
}

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:

   File.new("testfile").flock(File::LOCK_UN)   #=> 0

[Source]

/*
 *  call-seq:
 *     file.flock (locking_constant ) =>  0 or false
 *  
 *  Locks or unlocks a file according to <i>locking_constant</i> (a
 *  logical <em>or</em> of the values in the table below).
 *  Returns <code>false</code> if <code>File::LOCK_NB</code> 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:
 *
 *     File.new("testfile").flock(File::LOCK_UN)   #=> 0
 *     
 */

static VALUE
rb_file_flock(obj, operation)
    VALUE obj;
    VALUE operation;
{
#ifndef __CHECKER__
    rb_io_t *fptr;
    int op;

    rb_secure(2);
    op = NUM2INT(operation);
    GetOpenFile(obj, fptr);

    if (fptr->mode & FMODE_WRITABLE) {
        fflush(GetWriteFile(fptr));
    }
  retry:
    if (flock(fileno(fptr->f), op) < 0) {
        switch (errno) {
          case EAGAIN:
          case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
          case EWOULDBLOCK:
#endif
              return Qfalse;
          case EINTR:
#if defined(ERESTART)
          case ERESTART:
#endif
            goto retry;
        }
        rb_sys_fail(fptr->path);
    }
#endif
    return INT2FIX(0);
}

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

[Source]

/*
 *  call-seq:
 *     file.lstat   =>  stat
 *  
 *  Same as <code>IO#stat</code>, 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
 */

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

    rb_secure(2);
    GetOpenFile(obj, fptr);
    if (!fptr->path) return Qnil;
    if (lstat(fptr->path, &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return stat_new(&st);
#else
    return rb_io_stat(obj);
#endif
}

Returns the modification time for file.

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

[Source]

/*
 *  call-seq:
 *     file.mtime -> time
 *  
 *  Returns the modification time for <i>file</i>.
 *     
 *     File.new("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003
 *     
 */

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

    GetOpenFile(obj, fptr);
    if (fstat(fileno(fptr->f), &st) == -1) {
        rb_sys_fail(fptr->path);
    }
    return rb_time_new(st.st_mtime, 0);
}
o_chmod(p1)

Alias for chmod

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

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

[Source]

/*
 *  call-seq:
 *     file.path -> filename
 *  
 *  Returns the pathname used to create <i>file</i> as a string. Does
 *  not normalize the name.
 *     
 *     File.new("testfile").path               #=> "testfile"
 *     File.new("/tmp/../tmp/xxx", "w").path   #=> "/tmp/../tmp/xxx"
 *     
 */

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

    fptr = RFILE(rb_io_taint_check(obj))->fptr;
    rb_io_check_initialized(fptr);
    if (!fptr->path) return Qnil;
    return rb_tainted_str_new2(fptr->path);
}

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

[Source]

/*
 *  call-seq:
 *     file.truncate(integer)    => 0
 *  
 *  Truncates <i>file</i> to at most <i>integer</i> 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
 */

static VALUE
rb_file_truncate(obj, len)
    VALUE obj, len;
{
    rb_io_t *fptr;
    FILE *f;
    off_t pos;

    rb_secure(2);
    pos = NUM2OFFT(len);
    GetOpenFile(obj, fptr);
    if (!(fptr->mode & FMODE_WRITABLE)) {
        rb_raise(rb_eIOError, "not opened for writing");
    }
    f = GetWriteFile(fptr);
    fflush(f);
    fseeko(f, (off_t)0, SEEK_CUR);
#ifdef HAVE_FTRUNCATE
    if (ftruncate(fileno(f), pos) < 0)
        rb_sys_fail(fptr->path);
#else
# ifdef HAVE_CHSIZE
    if (chsize(fileno(f), pos) < 0)
        rb_sys_fail(fptr->path);
# else
    rb_notimplement();
# endif
#endif
    return INT2FIX(0);
}

[Validate]