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
.
Various constants for the methods in File can be found in File::Constants.
Defined Under Namespace
Modules: Constants Classes: Stat
Constant Summary collapse
- Separator =
separates directory parts in path
separator
- SEPARATOR =
separator
- ALT_SEPARATOR =
platform specific alternative separator
Qnil
- PATH_SEPARATOR =
path list separator
rb_obj_freeze(rb_str_new2(PATH_SEP))
Constants inherited from IO
IO::EWOULDBLOCKWaitReadable, IO::EWOULDBLOCKWaitWritable, IO::SEEK_CUR, IO::SEEK_DATA, IO::SEEK_END, IO::SEEK_HOLE, IO::SEEK_SET
Constants included from Constants
Constants::APPEND, Constants::BINARY, Constants::CREAT, Constants::DIRECT, Constants::DSYNC, Constants::EXCL, Constants::LOCK_EX, Constants::LOCK_NB, Constants::LOCK_SH, Constants::LOCK_UN, Constants::NOATIME, Constants::NOCTTY, Constants::NOFOLLOW, Constants::NONBLOCK, Constants::NULL, Constants::RDONLY, Constants::RDWR, Constants::RSYNC, Constants::SYNC, Constants::TRUNC, Constants::WRONLY
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 can be formed using both
File::SEPARATOR
andFile::ALT_SEPARATOR
as the separator whenFile::ALT_SEPARATOR
is notnil
. -
.birthtime(file_name) ⇒ Time
Returns the birth time for the named file.
-
.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(args) ⇒ 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
starting from the last period). -
.fnmatch(*args) ⇒ Object
Returns true if
path
matches againstpattern
. -
.fnmatch?(*args) ⇒ Boolean
Returns true if
path
matches againstpattern
. -
.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, ...) ⇒ String
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(*args) ⇒ Object
call-seq: IO.open(fd, mode=“r” [, opt]) -> io IO.open(fd, mode=“r” [, opt]) { |io| block } -> obj.
-
.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(*args) ⇒ Object
Returns the current umask value for this process.
-
.unlink(args) ⇒ 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. -
#birthtime ⇒ Time
Returns the birth time for file.
-
#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(locking_constant) ⇒ 0, false
Locks or unlocks a file according to locking_constant (a logical or of the values in the table below).
-
#initialize(*args) ⇒ Object
constructor
Opens the file named by
filename
according to the givenmode
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.
-
#to_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
#<<, #advise, #autoclose=, #autoclose?, #binmode, #binmode?, binread, binwrite, #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, #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, #lazy, #map, #max, #max_by, #member?, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #partition, #reduce, #reject, #reverse_each, #select, #slice_after, #slice_before, #slice_when, #sort, #sort_by, #take, #take_while, #to_a, #to_h, #zip
Constructor Details
#new(filename, mode = "r"[, opt]) ⇒ File #new(filename[, mode [, perm]][, opt]) ⇒ File
Opens the file named by filename
according to the given mode
and returns a new File object.
See IO.new for a description of mode
and opt
.
If a file is being created, permission bits may be given in perm
. These mode and permission bits are platform dependent; on Unix systems, see open(2) and chmod(2) man pages for details.
Examples
f = File.new("testfile", "r")
f = File.new("newfile", "w+")
f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 |
# File 'io.c', line 7636
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"
3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 |
# File 'file.c', line 3709
VALUE
rb_file_s_absolute_path(int argc, const 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_name can be an IO object.
File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 |
# File 'file.c', line 2076
static VALUE
rb_file_s_atime(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail_path(fname);
}
return stat_atime(&st);
}
|
.basename(file_name[, suffix]) ⇒ Object
Returns the last component of the filename given in file_name, which can be formed using both File::SEPARATOR
and File::ALT_SEPARATOR
as the separator when File::ALT_SEPARATOR
is not nil
. If suffix is given and present at the end of file_name, it is removed. If suffix is “.*”, any extension will be removed.
File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 |
# File 'file.c', line 4066
static VALUE
rb_file_s_basename(int argc, VALUE *argv)
{
VALUE fname, fext, basename;
const char *name, *p;
long f, n;
rb_encoding *enc;
if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
StringValue(fext);
enc = check_path_encoding(fext);
}
FilePathStringValue(fname);
if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
enc = rb_enc_get(fname);
fext = Qnil;
}
if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname)))
return rb_str_new_shared(fname);
p = ruby_enc_find_basename(name, &f, &n, enc);
if (n >= 0) {
if (NIL_P(fext)) {
f = n;
}
else {
const char *fp;
fp = StringValueCStr(fext);
if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
f = n;
}
RB_GC_GUARD(fext);
}
if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
}
basename = rb_str_new(p, f);
rb_enc_copy(basename, fname);
OBJ_INFECT(basename, fname);
return basename;
}
|
.birthtime(file_name) ⇒ Time
Returns the birth time for the named file.
file_name can be an IO object.
Note that on Windows (NTFS), returns creation time (birth time).
File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 |
# File 'file.c', line 2228
static VALUE
rb_file_s_birthtime(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail_path(fname);
}
return stat_birthtime(&st);
}
|
.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
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 |
# File 'file.c', line 2318
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")
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 |
# File 'file.c', line 2455
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);
arg.owner = to_uid(o);
arg.group = to_gid(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_name can be an IO object.
Note that on Windows (NTFS), returns creation time (birth time).
File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 |
# File 'file.c', line 2175
static VALUE
rb_file_s_ctime(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail_path(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
.
2841 2842 2843 2844 2845 2846 2847 2848 2849 |
# File 'file.c', line 2841
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 can be formed using both File::SEPARATOR
and File::ALT_SEPARATOR
as the separator when File::ALT_SEPARATOR
is not nil
.
File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4120 4121 4122 4123 4124 |
# File 'file.c', line 4120
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.("~oracle/bin") #=> "/home/oracle/bin"
A simple example of using dir_string
is as follows.
File.("ruby", "/usr/bin") #=> "/usr/bin/ruby"
A more complex example which also resolves parent directory is as follows. Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
File.("../../lib/mygem.rb", __FILE__)
#=> ".../path/to/project/lib/mygem.rb"
So first it resolves the parent of __FILE__, that is bin/, then go to the parent, the root of the project and appends lib/mygem.rb
.
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 |
# File 'file.c', line 3676
VALUE
rb_file_s_expand_path(int argc, const 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
starting from the last period).
If path
is a dotfile, or starts with a period, then the starting dot is not dealt with the start of the extension.
An empty string will also be returned when the period is the last character in path
.
File.extname("test.rb") #=> ".rb"
File.extname("a/b/d/test.rb") #=> ".rb"
File.extname("foo.") #=> ""
File.extname("test") #=> ""
File.extname(".profile") #=> ""
File.extname(".profile.sh") #=> ".sh"
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 |
# File 'file.c', line 4256
static VALUE
rb_file_s_extname(VALUE klass, VALUE fname)
{
const char *name, *e;
long len;
VALUE extname;
FilePathStringValue(fname);
name = StringValueCStr(fname);
len = RSTRING_LEN(fname);
e = ruby_enc_find_extname(name, &len, rb_enc_get(fname));
if (len <= 1)
return rb_str_new(0, 0);
extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */
OBJ_INFECT(extname, fname);
return extname;
}
|
.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. Equivalent to
/ .* /x
in regexp.*
-
Matches all files regular files
c*
-
Matches all files beginning with
c
*c
-
Matches all files ending with
c
*c*
-
Matches all files that have
c
in them (including at the beginning or end).
To match hidden files (that start with a
.
set the File::FNM_DOTMATCH flag. **
-
Matches directories recursively or files expansively.
?
-
Matches any one character. Equivalent to
/.{1}/
in regexp. [set]
-
Matches any one character in
set
. Behaves exactly like character sets in Regexp, including set negation ([^a-z]
). \
-
Escapes the next metacharacter.
{a,b}
-
Matches pattern a and pattern b if File::FNM_EXTGLOB flag is enabled. Behaves like a Regexp union (
(?:a|b)
).
flags
is a bitwise OR of the FNM_XXX
constants. The same glob pattern and flags are used by Dir::glob.
Examples:
File.fnmatch('cat', 'cat') #=> true # match entire string
File.fnmatch('cat', 'category') #=> false # only match partial string
File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported by default
File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true # { } is supported on FNM_EXTGLOB
File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character
File.fnmatch('c??t', 'cat') #=> false # ditto
File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters
File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto
File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression
File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!')
File.fnmatch('cat', 'CAT') #=> false # case sensitive
File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive
File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME
File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto
File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto
File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary
File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary
File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESCAPE makes '\' ordinary
File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression
File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading
File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default.
File.fnmatch('.*', '.profile') #=> true
rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
File.fnmatch(rbfiles, 'main.rb') #=> false
File.fnmatch(rbfiles, './main.rb') #=> false
File.fnmatch(rbfiles, 'lib/song.rb') #=> true
File.fnmatch('**.rb', 'main.rb') #=> true
File.fnmatch('**.rb', './main.rb') #=> false
File.fnmatch('**.rb', 'lib/song.rb') #=> true
File.fnmatch('*', 'dave/.profile') #=> true
pattern = '*' '/' '*'
File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false
File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
pattern = '**' '/' 'foo'
File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true
File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true
File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true
File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false
File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 |
# File 'dir.c', line 2365
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 (flags & FNM_EXTGLOB) {
struct brace_args args;
args.value = path;
args.flags = flags;
if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace,
(VALUE)&args, rb_enc_get(pattern)) > 0)
return Qtrue;
}
else {
rb_encoding *enc = rb_enc_compatible(pattern, path);
if (!enc) return Qfalse;
if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0)
return Qtrue;
}
RB_GC_GUARD(pattern);
return Qfalse;
}
|
.fnmatch(pattern, path, [flags]) ⇒ Boolean .fnmatch?(pattern, path, [flags]) ⇒ Boolean
Returns true if path
matches against pattern
. The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:
*
-
Matches any file. Can be restricted by other values in the glob. Equivalent to
/ .* /x
in regexp.*
-
Matches all files regular files
c*
-
Matches all files beginning with
c
*c
-
Matches all files ending with
c
*c*
-
Matches all files that have
c
in them (including at the beginning or end).
To match hidden files (that start with a
.
set the File::FNM_DOTMATCH flag. **
-
Matches directories recursively or files expansively.
?
-
Matches any one character. Equivalent to
/.{1}/
in regexp. [set]
-
Matches any one character in
set
. Behaves exactly like character sets in Regexp, including set negation ([^a-z]
). \
-
Escapes the next metacharacter.
{a,b}
-
Matches pattern a and pattern b if File::FNM_EXTGLOB flag is enabled. Behaves like a Regexp union (
(?:a|b)
).
flags
is a bitwise OR of the FNM_XXX
constants. The same glob pattern and flags are used by Dir::glob.
Examples:
File.fnmatch('cat', 'cat') #=> true # match entire string
File.fnmatch('cat', 'category') #=> false # only match partial string
File.fnmatch('c{at,ub}s', 'cats') #=> false # { } isn't supported by default
File.fnmatch('c{at,ub}s', 'cats', File::FNM_EXTGLOB) #=> true # { } is supported on FNM_EXTGLOB
File.fnmatch('c?t', 'cat') #=> true # '?' match only 1 character
File.fnmatch('c??t', 'cat') #=> false # ditto
File.fnmatch('c*', 'cats') #=> true # '*' match 0 or more characters
File.fnmatch('c*t', 'c/a/b/t') #=> true # ditto
File.fnmatch('ca[a-z]', 'cat') #=> true # inclusive bracket expression
File.fnmatch('ca[^t]', 'cat') #=> false # exclusive bracket expression ('^' or '!')
File.fnmatch('cat', 'CAT') #=> false # case sensitive
File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true # case insensitive
File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false # wildcard doesn't match '/' on FNM_PATHNAME
File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false # ditto
File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false # ditto
File.fnmatch('\?', '?') #=> true # escaped wildcard becomes ordinary
File.fnmatch('\a', 'a') #=> true # escaped ordinary remains ordinary
File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true # FNM_NOESCAPE makes '\' ordinary
File.fnmatch('[\?]', '?') #=> true # can escape inside bracket expression
File.fnmatch('*', '.profile') #=> false # wildcard doesn't match leading
File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true # period by default.
File.fnmatch('.*', '.profile') #=> true
rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string.
File.fnmatch(rbfiles, 'main.rb') #=> false
File.fnmatch(rbfiles, './main.rb') #=> false
File.fnmatch(rbfiles, 'lib/song.rb') #=> true
File.fnmatch('**.rb', 'main.rb') #=> true
File.fnmatch('**.rb', './main.rb') #=> false
File.fnmatch('**.rb', 'lib/song.rb') #=> true
File.fnmatch('*', 'dave/.profile') #=> true
pattern = '*' '/' '*'
File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false
File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
pattern = '**' '/' 'foo'
File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true
File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true
File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true
File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false
File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 |
# File 'dir.c', line 2365
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 (flags & FNM_EXTGLOB) {
struct brace_args args;
args.value = path;
args.flags = flags;
if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace,
(VALUE)&args, rb_enc_get(pattern)) > 0)
return Qtrue;
}
else {
rb_encoding *enc = rb_enc_compatible(pattern, path);
if (!enc) return Qfalse;
if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0)
return Qtrue;
}
RB_GC_GUARD(pattern);
return Qfalse;
}
|
.ftype(file_name) ⇒ String
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 |
# File 'file.c', line 2049
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_path(fname);
}
return rb_file_ftype(&st);
}
|
.join(string, ...) ⇒ String
Returns a new string formed by joining the strings using File::SEPARATOR
.
File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
4408 4409 4410 4411 4412 |
# File 'file.c', line 4408
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.
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 |
# File 'file.c', line 2391
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.
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 |
# File 'file.c', line 2533
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);
arg.owner = to_uid(o);
arg.group = to_gid(g);
n = apply2files(lchown_internal, rest, &arg);
return LONG2FIX(n);
}
|
.link(old_name, new_name) ⇒ 0
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 |
# File 'file.c', line 2723
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
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 |
# File 'file.c', line 1141
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_path(fname);
}
return rb_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_name can be an IO object.
File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 |
# File 'file.c', line 2124
static VALUE
rb_file_s_mtime(VALUE klass, VALUE fname)
{
struct stat st;
if (rb_stat(fname, &st) < 0) {
FilePathValue(fname);
rb_sys_fail_path(fname);
}
return stat_mtime(&st);
}
|
.open(*args) ⇒ Object
call-seq:
IO.open(fd, mode="r" [, opt]) -> io
IO.open(fd, mode="r" [, opt]) { |io| block } -> obj
With no associated block, IO.open
is a synonym for IO.new. If the optional code block is given, it will be passed io
as an argument, and the IO object will automatically be closed when the block terminates. In this instance, IO.open returns the value of the block.
See IO.new for a description of the fd
, mode
and opt
parameters.
6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 |
# File 'io.c', line 6378
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
4285 4286 4287 4288 4289 |
# File 'file.c', line 4285
static VALUE
rb_file_s_path(VALUE klass, VALUE fname)
{
return rb_get_path(fname);
}
|
.readlink(link_name) ⇒ Object
2786 2787 2788 2789 2790 |
# File 'file.c', line 2786
static VALUE
rb_file_s_readlink(VALUE klass, VALUE path)
{
return rb_readlink(path);
}
|
.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.
3942 3943 3944 3945 3946 3947 3948 |
# File 'file.c', line 3942
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.
3922 3923 3924 3925 3926 3927 3928 |
# File 'file.c', line 3922
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
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 |
# File 'file.c', line 2861
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"]
4302 4303 4304 4305 4306 4307 |
# File 'file.c', line 4302
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
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 |
# File 'file.c', line 1087
static VALUE
rb_file_s_stat(VALUE klass, VALUE fname)
{
struct stat st;
FilePathValue(fname);
if (rb_stat(fname, &st) < 0) {
rb_sys_fail_path(fname);
}
return rb_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
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 |
# File 'file.c', line 2754
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
4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 |
# File 'file.c', line 4430
static VALUE
rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
{
#ifdef HAVE_TRUNCATE
#define NUM2POS(n) NUM2OFFT(n)
off_t pos;
#else
#define NUM2POS(n) NUM2LONG(n)
long pos;
#endif
rb_secure(2);
pos = NUM2POS(len);
FilePathValue(path);
path = rb_str_encode_ospath(path);
#ifdef HAVE_TRUNCATE
if (truncate(StringValueCStr(path), pos) < 0)
rb_sys_fail_path(path);
#else /* defined(HAVE_CHSIZE) */
{
int tmpfd;
if ((tmpfd = rb_cloexec_open(StringValueCStr(path), 0, 0)) < 0) {
rb_sys_fail_path(path);
}
rb_update_max_fd(tmpfd);
if (chsize(tmpfd, pos) < 0) {
close(tmpfd);
rb_sys_fail_path(path);
}
close(tmpfd);
}
#endif
return INT2FIX(0);
#undef NUM2POS
}
|
.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
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 |
# File 'file.c', line 2911
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_check_arity(argc, 0, 1);
}
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
.
2841 2842 2843 2844 2845 2846 2847 2848 2849 |
# File 'file.c', line 2841
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.
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 |
# File 'file.c', line 2666
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
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 |
# File 'file.c', line 2099
static VALUE
rb_file_atime(VALUE obj)
{
rb_io_t *fptr;
struct stat st;
GetOpenFile(obj, fptr);
if (fstat(fptr->fd, &st) == -1) {
rb_sys_fail_path(fptr->pathv);
}
return stat_atime(&st);
}
|
#birthtime ⇒ Time
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 |
# File 'file.c', line 2256
static VALUE
rb_file_birthtime(VALUE obj)
{
rb_io_t *fptr;
struct stat st;
GetOpenFile(obj, fptr);
if (fstat(fptr->fd, &st) == -1) {
rb_sys_fail_path(fptr->pathv);
}
return stat_birthtime(&st);
}
|
#chmod(mode_int) ⇒ 0
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 |
# File 'file.c', line 2347
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)
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 |
# File 'file.c', line 2486
static VALUE
rb_file_chown(VALUE obj, VALUE owner, VALUE group)
{
rb_io_t *fptr;
rb_uid_t o;
rb_gid_t g;
#ifndef HAVE_FCHOWN
VALUE path;
#endif
rb_secure(2);
o = to_uid(owner);
g = to_gid(group);
GetOpenFile(obj, fptr);
#ifndef HAVE_FCHOWN
if (NIL_P(fptr->pathv)) return Qnil;
path = rb_str_encode_ospath(fptr->pathv);
if (chown(RSTRING_PTR(path), o, g) == -1)
rb_sys_fail_path(fptr->pathv);
#else
if (fchown(fptr->fd, o, g) == -1)
rb_sys_fail_path(fptr->pathv);
#endif
return INT2FIX(0);
}
|
#ctime ⇒ Time
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 |
# File 'file.c', line 2200
static VALUE
rb_file_ctime(VALUE obj)
{
rb_io_t *fptr;
struct stat st;
GetOpenFile(obj, fptr);
if (fstat(fptr->fd, &st) == -1) {
rb_sys_fail_path(fptr->pathv);
}
return stat_ctime(&st);
}
|
#flock(locking_constant) ⇒ 0, false
Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false
if File::LOCK_NB
is specified and the operation would otherwise have blocked. Not available on all platforms.
Locking constants (in class File):
LOCK_EX | Exclusive lock. Only one process may hold an
| exclusive lock for a given file at a time.
----------+------------------------------------------------
LOCK_NB | Don't block when locking. May be combined
| with other lock options using logical or.
----------+------------------------------------------------
LOCK_SH | Shared lock. Multiple processes may each hold a
| shared lock for a given file at the same time.
----------+------------------------------------------------
LOCK_UN | Unlock.
Example:
# update a counter using write lock
# don't use "w" because it truncates the file before lock.
File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
f.flock(File::LOCK_EX)
value = f.read.to_i + 1
f.rewind
f.write("#{value}\n")
f.flush
f.truncate(f.pos)
}
# read the counter using read lock
File.open("counter", "r") {|f|
f.flock(File::LOCK_SH)
p f.read
}
4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 |
# File 'file.c', line 4596
static VALUE
rb_file_flock(VALUE obj, VALUE operation)
{
rb_io_t *fptr;
int op[2], op1;
struct timeval time;
rb_secure(2);
op[1] = op1 = NUM2INT(operation);
GetOpenFile(obj, fptr);
op[0] = fptr->fd;
if (fptr->mode & FMODE_WRITABLE) {
rb_io_flush_raw(obj, 0);
}
while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) {
switch (errno) {
case EAGAIN:
case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
if (op1 & LOCK_NB) return Qfalse;
time.tv_sec = 0;
time.tv_usec = 100 * 1000; /* 0.1 sec */
rb_thread_wait_for(time);
rb_io_check_closed(fptr);
continue;
case EINTR:
#if defined(ERESTART)
case ERESTART:
#endif
break;
default:
rb_sys_fail_path(fptr->pathv);
}
}
return INT2FIX(0);
}
|
#lstat ⇒ Object
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 |
# File 'file.c', line 1173
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 rb_stat_new(&st);
#else
return rb_io_stat(obj);
#endif
}
|
#mtime ⇒ Time
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 |
# File 'file.c', line 2146
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 #to_path ⇒ Object
382 383 384 385 386 387 388 389 390 391 |
# File 'file.c', line 382
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
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 |
# File 'file.c', line 2282
static VALUE
rb_file_size(VALUE obj)
{
rb_io_t *fptr;
struct stat st;
GetOpenFile(obj, fptr);
if (fptr->mode & FMODE_WRITABLE) {
rb_io_flush_raw(obj, 0);
}
if (fstat(fptr->fd, &st) == -1) {
rb_sys_fail_path(fptr->pathv);
}
return OFFT2NUM(st.st_size);
}
|
#path ⇒ Object #to_path ⇒ Object
382 383 384 385 386 387 388 389 390 391 |
# File 'file.c', line 382
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
4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 |
# File 'file.c', line 4485
static VALUE
rb_file_truncate(VALUE obj, VALUE len)
{
rb_io_t *fptr;
#if defined(HAVE_FTRUNCATE)
#define NUM2POS(n) NUM2OFFT(n)
off_t pos;
#else
#define NUM2POS(n) NUM2LONG(n)
long pos;
#endif
rb_secure(2);
pos = NUM2POS(len);
GetOpenFile(obj, fptr);
if (!(fptr->mode & FMODE_WRITABLE)) {
rb_raise(rb_eIOError, "not opened for writing");
}
rb_io_flush_raw(obj, 0);
#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_path(fptr->pathv);
#endif
return INT2FIX(0);
#undef NUM2POS
}
|