Class: File
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
.
Defined Under Namespace
Classes: Stat
Constant Summary collapse
- Separator =
separator
- SEPARATOR =
separator
- ALT_SEPARATOR =
Qnil
- PATH_SEPARATOR =
rb_obj_freeze(rb_str_new2(PATH_SEP))
Constants inherited from IO
IO::SEEK_CUR, IO::SEEK_END, IO::SEEK_SET
Class Method Summary collapse
-
.absolute_path(file_name[, dir_string]) ⇒ Object
Converts a pathname to an absolute pathname.
-
.atime(file_name) ⇒ Time
Returns the last access time for the named file as a Time object).
-
.basename(file_name[, suffix]) ⇒ Object
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. -
.chmod(mode_int, file_name, ...) ⇒ Integer
Changes permission bits on the named file(s) to the bit pattern represented by mode_int.
-
.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.
-
.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).
-
.delete ⇒ Object
Deletes the named files, returning the number of names passed as arguments.
-
.dirname(file_name) ⇒ Object
Returns all components of the filename given in file_name except the last one.
-
.expand_path(file_name[, dir_string]) ⇒ Object
Converts a pathname to an absolute pathname.
-
.extname(path) ⇒ String
Returns the extension (the portion of file name in path after the period).
-
.fnmatch? ⇒ Object
Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing.
-
.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
". -
.join(string, ...) ⇒ Object
Returns a new string formed by joining the strings using
File::SEPARATOR
. -
.lchmod(mode_int, file_name, ...) ⇒ Integer
Equivalent to
File::chmod
, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). -
.lchown(owner_int, group_int, file_name, ..) ⇒ Integer
Equivalent to
File::chown
, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). -
.link(old_name, new_name) ⇒ 0
Creates a new name for an existing file using a hard link.
-
.lstat(file_name) ⇒ Object
Same as
File::stat
, but does not follow the last symbolic link. -
.mtime(file_name) ⇒ Time
Returns the modification time for the named file as a Time object.
-
.open ⇒ Object
With no associated block,
open
is a synonym forFile.new
. -
.path(path) ⇒ String
Returns the string representation of the path.
-
.readlink(link_name) ⇒ Object
Returns the name of the file referenced by the given link.
-
.realdirpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual filesystem.
-
.realpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual filesystem not containing symlinks or useless dots.
-
.rename(old_name, new_name) ⇒ 0
Renames the given file to the new name.
-
.split(file_name) ⇒ Array
Splits the given string into a directory and a file component and returns them in a two-element array.
-
.stat(file_name) ⇒ Object
Returns a
File::Stat
object for the named file (seeFile::Stat
). -
.symlink(old_name, new_name) ⇒ 0
Creates a symbolic link called new_name for the existing file old_name.
-
.truncate(file_name, integer) ⇒ 0
Truncates the file file_name to be at most integer bytes long.
-
.umask ⇒ Object
Returns the current umask value for this process.
-
.unlink ⇒ Object
Deletes the named files, returning the number of names passed as arguments.
-
.utime(atime, mtime, file_name, ...) ⇒ Integer
Sets the access and modification times of each named file to the first two arguments.
Instance Method Summary collapse
-
#atime ⇒ Time
Returns the last access time (a
Time
object) for file, or epoch if file has not been accessed. -
#chmod(mode_int) ⇒ 0
Changes permission bits on file to the bit pattern represented by mode_int.
-
#chown(owner_int, group_int) ⇒ 0
Changes the owner and group of file to the given numeric owner and group id's.
-
#ctime ⇒ Time
Returns the change time for file (that is, the time directory information about the file was changed, not the file itself).
-
#flock ⇒ Object
Locks or unlocks a file according to locking_constant (a logical or of the values in the table below).
-
#initialize ⇒ Object
constructor
Opens the file named by filename according to mode (default is "r") and returns a new
File
object. -
#lstat ⇒ Object
Same as
IO#stat
, but does not follow the last symbolic link. -
#mtime ⇒ Time
Returns the modification time for file.
-
#path ⇒ Object
Returns the pathname used to create file as a string.
-
#size ⇒ Integer
Returns the size of file in bytes.
-
#path ⇒ Object
Returns the pathname used to create file as a string.
-
#truncate(integer) ⇒ 0
Truncates file to at most integer bytes.
Methods inherited from IO
#<<, #autoclose=, #autoclose?, #binmode, #binmode?, binread, #bytes, #chars, #close, #close_on_exec=, #close_on_exec?, #close_read, #close_write, #closed?, #codepoints, copy_stream, #each, #each_byte, #each_char, #each_codepoint, #each_line, #eof, #eof?, #external_encoding, #fcntl, #fdatasync, #fileno, #flush, for_fd, foreach, #fsync, #getbyte, #getc, #gets, #initialize_copy, #inspect, #internal_encoding, #ioctl, #isatty, #lineno, #lineno=, #lines, new, #pid, pipe, popen, #pos, #pos=, #print, #printf, #putc, #puts, read, #read, #read_nonblock, #readbyte, #readchar, #readline, #readlines, readlines, #readpartial, #reopen, #rewind, #seek, select, #set_encoding, #stat, #sync, #sync=, sysopen, #sysread, #sysseek, #syswrite, #tell, #to_io, try_convert, #tty?, #ungetbyte, #ungetc, #write, #write_nonblock
Methods included from Enumerable
#all?, #any?, #chunk, #collect, #collect_concat, #count, #cycle, #detect, #drop, #drop_while, #each_cons, #each_entry, #each_slice, #each_with_index, #each_with_object, #entries, #find, #find_all, #find_index, #first, #flat_map, #grep, #group_by, #include?, #inject, #map, #max, #max_by, #member?, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #partition, #reduce, #reject, #reverse_each, #select, #slice_before, #sort, #sort_by, #take, #take_while, #to_a, #zip
Constructor Details
#new(filename, mode = "r"[, opt]) ⇒ File #new(filename[, mode [, perm]][, opt]) ⇒ File
Opens the file named by filename according to mode (default is "r") and returns a new File
object.
Parameters
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.
Optional opt parameter is same as in <code.IO.open</code>.
Examples
f = File.new("testfile", "r")
f = File.new("newfile", "w+")
f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
|
# File 'io.c'
/*
* call-seq:
* File.new(filename, mode="r" [, opt]) -> file
* File.new(filename [, mode [, perm]] [, opt]) -> file
*
* Opens the file named by _filename_ according to
* _mode_ (default is ``r'') and returns a new
* <code>File</code> object.
*
* === Parameters
* 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.
*
* Optional _opt_ parameter is same as in <code.IO.open</code>.
*
* === Examples
*
* 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(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;
}
|
Class Method Details
.absolute_path(file_name[, dir_string]) ⇒ Object
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"
|
# File 'file.c'
/*
* call-seq:
* File.absolute_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. If the given pathname starts with a ``<code>~</code>''
* it is NOT expanded, it is treated as a normal directory name.
*
* File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
*/
VALUE
rb_file_s_absolute_path(int argc, VALUE *argv)
{
VALUE fname, dname;
if (argc == 1) {
return rb_file_absolute_path(argv[0], Qnil);
}
rb_scan_args(argc, argv, "11", &fname, &dname);
return rb_file_absolute_path(fname, dname);
}
|
.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
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail(RSTRING_PTR(fname));
}
return stat_atime(&st);
}
|
.basename(file_name[, suffix]) ⇒ Object
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"
|
# File 'file.c'
/*
* 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(int argc, VALUE *argv)
{
VALUE fname, fext, basename;
const char *name, *p;
long f, n;
if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
rb_encoding *enc;
StringValue(fext);
if (!rb_enc_asciicompat(enc = rb_enc_get(fext))) {
rb_raise(rb_eEncCompatError, "ascii incompatible character encodings: %s",
rb_enc_name(enc));
}
}
FilePathStringValue(fname);
if (!NIL_P(fext)) rb_enc_check(fname, fext);
if (RSTRING_LEN(fname) == 0 || !*(name = RSTRING_PTR(fname)))
return rb_str_new_shared(fname);
p = ruby_find_basename(name, &f, &n);
if (n >= 0) {
if (NIL_P(fext) || !(f = rmext(p, n, StringValueCStr(fext)))) {
f = n;
}
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;
}
|
.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
|
# File 'file.c'
/*
* 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(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);
}
|
.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")
|
# File 'file.c'
/*
* 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(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 = NUM2UIDT(o);
}
if (NIL_P(g)) {
arg.group = -1;
}
else {
arg.group = NUM2GIDT(g);
}
n = apply2files(chown_internal, rest, &arg);
return LONG2FIX(n);
}
|
.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
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail(RSTRING_PTR(fname));
}
return stat_ctime(&st);
}
|
.delete(file_name, ...) ⇒ Integer .unlink(file_name, ...) ⇒ Integer
Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir
.
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE args)
{
long n;
rb_secure(2);
n = apply2files(unlink_internal, args, 0);
return LONG2FIX(n);
}
|
.dirname(file_name) ⇒ Object
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"
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
return rb_file_dirname(fname);
}
|
.expand_path(file_name[, dir_string]) ⇒ Object
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"
|
# File 'file.c'
/*
* 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(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);
}
|
.extname(path) ⇒ String
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") #=> ""
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
const char *name, *e;
long len;
VALUE extname;
FilePathStringValue(fname);
name = StringValueCStr(fname);
e = ruby_find_extname(name, &len);
if (len <= 1)
return rb_str_new(0, 0);
extname = rb_str_new(e, len); /* keep the dot, too! */
rb_enc_copy(extname, fname);
OBJ_INFECT(extname, fname);
return extname;
}
|
.fnmatch(pattern, path, [flags]) ⇒ Boolean .fnmatch?(pattern, path, [flags]) ⇒ Boolean
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 withc
;*c
will match all files ending withc
; andc
will match all files that havec
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
|
# File 'dir.c'
/*
* 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(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);
FilePathStringValue(path);
if (fnmatch(RSTRING_PTR(pattern), rb_enc_get(pattern), RSTRING_PTR(path),
flags) == 0)
return Qtrue;
return Qfalse;
}
|
.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"
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
struct stat st;
rb_secure(2);
FilePathValue(fname);
fname = rb_str_encode_ospath(fname);
if (lstat(StringValueCStr(fname), &st) == -1) {
rb_sys_fail(RSTRING_PTR(fname));
}
return rb_file_ftype(&st);
}
|
.join(string, ...) ⇒ Object
Returns a new string formed by joining the strings using File::SEPARATOR
.
File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE args)
{
return rb_file_join(args, separator);
}
|
.lchmod(mode_int, file_name, ...) ⇒ Integer
Equivalent to File::chmod
, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). Often not available.
|
# File 'file.c'
/*
* 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(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);
}
|
.lchown(owner_int, group_int, file_name, ..) ⇒ Integer
Equivalent to File::chown
, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). Often not available. Returns number of files in the argument list.
|
# File 'file.c'
/*
* 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(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 = NUM2UIDT(o);
}
if (NIL_P(g)) {
arg.group = -1;
}
else {
arg.group = NUM2GIDT(g);
}
n = apply2files(lchown_internal, rest, &arg);
return LONG2FIX(n);
}
|
.link(old_name, new_name) ⇒ 0
Creates a new name for an existing file using a hard link. Will not overwrite new_name if it already exists (raising a subclass of SystemCallError
). Not available on all platforms.
File.link("testfile", ".testfile") #=> 0
IO.readlines(".testfile")[0] #=> "This is line one\n"
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE from, VALUE to)
{
rb_secure(2);
FilePathValue(from);
FilePathValue(to);
from = rb_str_encode_ospath(from);
to = rb_str_encode_ospath(to);
if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
sys_fail2(from, to);
}
return INT2FIX(0);
}
|
.lstat(file_name) ⇒ Object
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
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
#ifdef HAVE_LSTAT
struct stat st;
rb_secure(2);
FilePathValue(fname);
fname = rb_str_encode_ospath(fname);
if (lstat(StringValueCStr(fname), &st) == -1) {
rb_sys_fail(RSTRING_PTR(fname));
}
return stat_new(&st);
#else
return rb_file_s_stat(klass, fname);
#endif
}
|
.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
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail(RSTRING_PTR(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 File.new
. If the optional code block is given, it will be passed file as an argument, and the File object will automatically be closed when the block terminates. In this instance, File.open
returns the value of the block.
|
# File 'io.c'
/*
* Document-method: IO::open
*
* call-seq:
* IO.open(fd, mode_string="r" [, opt] ) -> io
* IO.open(fd, mode_string="r" [, opt] ) {|io| block } -> obj
*
* With no associated block, <code>open</code> is a synonym for
* <code>IO.new</code>. If the optional code block is given, it will
* be passed <i>io</i> as an argument, and the IO object will
* automatically be closed when the block terminates. In this instance,
* <code>IO.open</code> returns the value of the block.
*
*/
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;
}
|
.path(path) ⇒ String
Returns the string representation of the path
File.path("/dev/null") #=> "/dev/null"
File.path(Pathname.new("/tmp")) #=> "/tmp"
|
# File 'file.c'
/*
* call-seq:
* File.path(path) -> string
*
* Returns the string representation of the path
*
* File.path("/dev/null") #=> "/dev/null"
* File.path(Pathname.new("/tmp")) #=> "/tmp"
*
*/
static VALUE
rb_file_s_path(VALUE klass, VALUE fname)
{
return rb_get_path(fname);
}
|
.readlink(link_name) ⇒ Object
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"
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE path)
{
char *buf;
int size = 100;
ssize_t rv;
VALUE v;
rb_secure(2);
FilePathValue(path);
path = rb_str_encode_ospath(path);
buf = xmalloc(size);
while ((rv = readlink(RSTRING_PTR(path), buf, size)) == size
#ifdef _AIX
|| (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
#endif
) {
size *= 2;
buf = xrealloc(buf, size);
}
if (rv < 0) {
xfree(buf);
rb_sys_fail_path(path);
}
v = rb_filesystem_str_new(buf, rv);
xfree(buf);
return v;
}
|
.realdirpath(pathname[, dir_string]) ⇒ Object
Returns the real (absolute) pathname of pathname in the actual filesystem.
The real pathname doesn't contain symlinks or useless dots.
If _dir_string_ is given, it is used as a base directory
for interpreting relative pathname instead of the current directory.
The last component of the real pathname can be nonexistent.
|
# File 'file.c'
/*
* call-seq:
* File.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.
*/
static VALUE
rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass)
{
VALUE path, basedir;
rb_scan_args(argc, argv, "11", &path, &basedir);
return rb_realpath_internal(basedir, path, 0);
}
|
.realpath(pathname[, dir_string]) ⇒ Object
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.
|
# File 'file.c'
/*
* call-seq:
* File.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.
*/
static VALUE
rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
{
VALUE path, basedir;
rb_scan_args(argc, argv, "11", &path, &basedir);
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
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE from, VALUE to)
{
const char *src, *dst;
VALUE f, t;
rb_secure(2);
FilePathValue(from);
FilePathValue(to);
f = rb_str_encode_ospath(from);
t = rb_str_encode_ospath(to);
src = StringValueCStr(f);
dst = StringValueCStr(t);
#if defined __CYGWIN__
errno = 0;
#endif
if (rename(src, dst) < 0) {
#if defined DOSISH
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);
}
|
.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 File::dirname
and File::basename
.
File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE path)
{
FilePathStringValue(path); /* get rid of converting twice */
return rb_assoc_new(rb_file_s_dirname(Qnil, path), rb_file_s_basename(1,&path));
}
|
.stat(file_name) ⇒ Object
Returns a File::Stat
object for the named file (see File::Stat
).
File.stat("testfile").mtime #=> Tue Apr 08 12:58:04 CDT 2003
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE fname)
{
struct stat st;
rb_secure(4);
FilePathValue(fname);
if (rb_stat(fname, &st) < 0) {
rb_sys_fail(RSTRING_PTR(fname));
}
return stat_new(&st);
}
|
.symlink(old_name, new_name) ⇒ 0
Creates a symbolic link called new_name for the existing file old_name. Raises a NotImplemented
exception on platforms that do not support symbolic links.
File.symlink("testfile", "link2test") #=> 0
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE from, VALUE to)
{
rb_secure(2);
FilePathValue(from);
FilePathValue(to);
from = rb_str_encode_ospath(from);
to = rb_str_encode_ospath(to);
if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
sys_fail2(from, to);
}
return INT2FIX(0);
}
|
.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
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE path, VALUE len)
{
off_t pos;
rb_secure(2);
pos = NUM2OFFT(len);
FilePathValue(path);
path = rb_str_encode_ospath(path);
#ifdef HAVE_TRUNCATE
if (truncate(StringValueCStr(path), pos) < 0)
rb_sys_fail(RSTRING_PTR(path));
#else /* defined(HAVE_CHSIZE) */
{
int tmpfd;
if ((tmpfd = open(StringValueCStr(path), 0)) < 0) {
rb_sys_fail(RSTRING_PTR(path));
}
if (chsize(tmpfd, pos) < 0) {
close(tmpfd);
rb_sys_fail(RSTRING_PTR(path));
}
close(tmpfd);
}
#endif
return INT2FIX(0);
}
|
.umask ⇒ Integer .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
|
# File 'file.c'
/*
* 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(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 (%d for 0..1)", argc);
}
return INT2FIX(omask);
}
|
.delete(file_name, ...) ⇒ Integer .unlink(file_name, ...) ⇒ Integer
Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir
.
|
# File 'file.c'
/*
* 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(VALUE klass, VALUE args)
{
long n;
rb_secure(2);
n = apply2files(unlink_internal, args, 0);
return LONG2FIX(n);
}
|
.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.
|
# File 'file.c'
/*
* 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(int argc, VALUE *argv)
{
VALUE rest;
struct utime_args args;
struct timespec tss[2], *tsp = NULL;
long n;
rb_secure(2);
rb_scan_args(argc, argv, "2*", &args.atime, &args.mtime, &rest);
if (!NIL_P(args.atime) || !NIL_P(args.mtime)) {
tsp = tss;
tsp[0] = rb_time_timespec(args.atime);
tsp[1] = rb_time_timespec(args.mtime);
}
args.tsp = tsp;
n = apply2files(utime_internal, rest, &args);
return LONG2FIX(n);
}
|
Instance Method Details
#atime ⇒ Time
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
|
# File 'file.c'
/*
* 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(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);
}
|
#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
|
# File 'file.c'
/*
* 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(VALUE obj, VALUE vmode)
{
rb_io_t *fptr;
int mode;
#ifndef HAVE_FCHMOD
VALUE path;
#endif
rb_secure(2);
mode = NUM2INT(vmode);
GetOpenFile(obj, fptr);
#ifdef HAVE_FCHMOD
if (fchmod(fptr->fd, mode) == -1)
rb_sys_fail_path(fptr->pathv);
#else
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)
|
# File 'file.c'
/*
* 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(VALUE obj, VALUE owner, VALUE group)
{
rb_io_t *fptr;
int o, g;
#ifndef HAVE_FCHOWN
VALUE path;
#endif
rb_secure(2);
o = NIL_P(owner) ? -1 : NUM2INT(owner);
g = NIL_P(group) ? -1 : NUM2INT(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);
}
|
#ctime ⇒ Time
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
|
# File 'file.c'
/*
* 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(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 ⇒ Object
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
}
|
# File 'file.c'
/*
* 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:
*
* # 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
* }
*
*/
static VALUE
rb_file_flock(VALUE obj, VALUE operation)
{
rb_io_t *fptr;
int op[2], op1;
rb_secure(2);
op[1] = op1 = NUM2INT(operation);
GetOpenFile(obj, fptr);
op[0] = fptr->fd;
if (fptr->mode & FMODE_WRITABLE) {
rb_io_flush(obj);
}
while ((int)rb_thread_blocking_region(rb_thread_flock, op, RUBY_UBF_IO, 0) < 0) {
switch (errno) {
case EAGAIN:
case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
if (op1 & LOCK_NB) return Qfalse;
rb_thread_polling();
rb_io_check_closed(fptr);
continue;
case EINTR:
#if defined(ERESTART)
case ERESTART:
#endif
break;
default:
rb_sys_fail_path(fptr->pathv);
}
}
return INT2FIX(0);
}
|
#lstat ⇒ Object
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
|
# File 'file.c'
/*
* 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(VALUE obj)
{
#ifdef HAVE_LSTAT
rb_io_t *fptr;
struct stat st;
VALUE path;
rb_secure(2);
GetOpenFile(obj, fptr);
if (NIL_P(fptr->pathv)) return Qnil;
path = rb_str_encode_ospath(fptr->pathv);
if (lstat(RSTRING_PTR(path), &st) == -1) {
rb_sys_fail_path(fptr->pathv);
}
return stat_new(&st);
#else
return rb_io_stat(obj);
#endif
}
|
#mtime ⇒ Time
Returns the modification time for file.
File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
|
# File 'file.c'
/*
* 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(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);
}
|
#path ⇒ Object
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"
|
# File 'file.c'
/*
* 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(VALUE obj)
{
rb_io_t *fptr;
fptr = RFILE(rb_io_taint_check(obj))->fptr;
rb_io_check_initialized(fptr);
if (NIL_P(fptr->pathv)) return Qnil;
return rb_obj_taint(rb_str_dup(fptr->pathv));
}
|
#size ⇒ Integer
Returns the size of file in bytes.
File.new("testfile").size #=> 66
|
# File 'file.c'
/*
* call-seq:
* file.size -> integer
*
* Returns the size of <i>file</i> in bytes.
*
* File.new("testfile").size #=> 66
*
*/
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(obj);
}
if (fstat(fptr->fd, &st) == -1) {
rb_sys_fail_path(fptr->pathv);
}
return OFFT2NUM(st.st_size);
}
|
#path ⇒ Object
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"
|
# File 'file.c'
/*
* 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(VALUE obj)
{
rb_io_t *fptr;
fptr = RFILE(rb_io_taint_check(obj))->fptr;
rb_io_check_initialized(fptr);
if (NIL_P(fptr->pathv)) return Qnil;
return rb_obj_taint(rb_str_dup(fptr->pathv));
}
|
#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
|
# File 'file.c'
/*
* 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(VALUE obj, VALUE len)
{
rb_io_t *fptr;
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");
}
rb_io_flush(obj);
#ifdef HAVE_FTRUNCATE
if (ftruncate(fptr->fd, pos) < 0)
rb_sys_fail_path(fptr->pathv);
#else /* defined(HAVE_CHSIZE) */
if (chsize(fptr->fd, pos) < 0)
rb_sys_fail(fptr->pathv);
#endif
return INT2FIX(0);
}
|