Class: File
Relationships & Source Files | |
Namespace Children | |
Modules:
| |
Classes:
| |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
::IO
|
|
Instance Chain:
|
|
Inherits: | IO |
Defined in: | file.c, dir.c, io.c |
Overview
A File
is an abstraction of any file object accessible by the program and is closely associated with class ::IO File
includes the methods of module ::FileTest as class methods, allowing you to write (for example) File.exist?("foo")
.
In the description of File
methods, permission bits are a platform-specific set of bits that indicate permissions of a file. On Unix-based systems, permissions are viewed as a set of three octets, for the owner, the group, and the rest of the world. For each of these entities, permissions may be set to read, write, or execute the file:
The permission bits 0644
(in octal) would thus be interpreted as read/write for owner, and read-only for group and other. Higher-order bits may also be used to indicate the type of file (plain, directory, pipe, socket, and so on) and various other special features. If the permissions are for a directory, the meaning of the execute bit changes; when set the directory can be searched.
On non-Posix operating systems, there may be only the ability to make a file read-only or read-write. In this case, the remaining permission bits will be synthesized to resemble typical values. For instance, on Windows NT the default permission bits are 0644
, which means read/write for owner, read-only for all others. The only change that can be made is to make the file read-only, which is reported as 0444
.
Various constants for the methods in File
can be found in Constants.
Constant Summary
-
ALT_SEPARATOR =
platform specific alternative separator
rb_obj_freeze(rb_usascii_str_new2(file_alt_separator))
-
PATH_SEPARATOR =
path list separator
rb_obj_freeze(rb_str_new2(PATH_SEP))
-
SEPARATOR =
# File 'file.c', line 5911separator
-
Separator =
separates directory parts in path
separator
Constants - Included
APPEND, BINARY, CREAT, DIRECT, DSYNC, EXCL, LOCK_EX, LOCK_NB, LOCK_SH, LOCK_UN, NOATIME, NOCTTY, NOFOLLOW, NONBLOCK, NULL, RDONLY, RDWR, RSYNC, SYNC, TRUNC, WRONLY
::IO - Inherited
Class Attribute Summary
-
.directory?(file_name) ⇒ Boolean
readonly
Alias for Dir.exist?.
Class Method Summary
-
.absolute_path(file_name [, dir_string] ) ⇒ File
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] ) ⇒ base_name
Returns the last component of the filename given in file_name, which can be formed using both SEPARATOR and ALT_SEPARATOR as the separator when ALT_SEPARATOR is not
nil
. -
.birthtime(file_name) ⇒ Time
Returns the birth time for the named file.
-
.blockdev?(file_name) ⇒ Boolean
Returns
true
if the named file is a block device. -
.chardev?(file_name) ⇒ Boolean
Returns
true
if the named file is a character device. -
.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(file_name, ...) ⇒ Integer
(also: .unlink)
Deletes the named files, returning the number of names passed as arguments.
-
.dirname(file_name) ⇒ dir_name
Returns all components of the filename given in file_name except the last one.
-
.executable?(file_name) ⇒ Boolean
Returns
true
if the named file is executable by the effective user id of this process. -
.executable_real?(file_name) ⇒ Boolean
Returns
true
if the named file is executable by the real user id of this process. -
.exist?(file_name) ⇒ Boolean
Return
true
if the named file exists. -
.exists?(file_name) ⇒ Boolean
Deprecated method.
-
.expand_path(file_name [, dir_string] ) ⇒ File
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).
-
.file?(file) ⇒ Boolean
Returns
true
if the namedfile
exists and is a regular file. -
.fnmatch(pattern, path, [flags]) ⇒ Boolean
(also: .fnmatch?)
Returns true if .path matches against
pattern
. -
.fnmatch?(pattern, path, [flags]) ⇒ Boolean
Alias for .fnmatch.
-
.ftype(file_name) ⇒ String
Identifies the type of the named file; the return string is one of “
file
'', “directory
'', “characterSpecial
'', “blockSpecial
'', “fifo
'', “link
'', “socket
'', or “unknown
''. -
.grpowned?(file_name) ⇒ Boolean
Returns
true
if the named file exists and the effective group id of the calling process is the owner of the file. -
.identical?(file_1, file_2) ⇒ Boolean
Returns
true
if the named files are identical. -
.join(string, ...) ⇒ String
Returns a new string formed by joining the strings using SEPARATOR.
-
.lchmod(mode_int, file_name, ...) ⇒ Integer
Equivalent to .chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link).
-
.lchown(owner_int, group_int, file_name,..) ⇒ Integer
Equivalent to .chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link).
-
.link(old_name, new_name) ⇒ 0
Creates a new name for an existing file using a hard link.
-
.lstat(file_name) ⇒ stat
Same as .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.
-
.new(filename, mode="r" [, opt]) ⇒ File
constructor
Opens the file named by
filename
according to the givenmode
and returns a newFile
object. -
.open(filename, mode="r" [, opt]) ⇒ File
With no associated block,
open
is a synonym for .new. -
.owned?(file_name) ⇒ Boolean
Returns
true
if the named file exists and the effective used id of the calling process is the owner of the file. -
.path(path) ⇒ String
Returns the string representation of the path.
-
.pipe?(file_name) ⇒ Boolean
Returns
true
if the named file is a pipe. -
.readable?(file_name) ⇒ Boolean
Returns
true
if the named file is readable by the effective user id of this process. -
.readable_real?(file_name) ⇒ Boolean
Returns
true
if the named file is readable by the real user id of this process. -
.readlink(link_name) ⇒ File
Returns the name of the file referenced by the given link.
-
.realdirpath(pathname [, dir_string]) ⇒ real_pathname
Returns the real (absolute) pathname of pathname in the actual filesystem.
-
.realpath(pathname [, dir_string]) ⇒ real_pathname
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.
-
.setgid?(file_name) ⇒ Boolean
Returns
true
if the named file has the setgid bit set. -
.setuid?(file_name) ⇒ Boolean
Returns
true
if the named file has the setuid bit set. -
.size(file_name) ⇒ Integer
Returns the size of
file_name
. -
.size?(file_name) ⇒ Integer?
Returns
nil
iffile_name
doesn't exist or has zero size, the size of the file otherwise. -
.socket?(file_name) ⇒ Boolean
Returns
true
if the named file is a socket. -
.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) ⇒ stat
-
.sticky?(file_name) ⇒ Boolean
Returns
true
if the named file has the sticky bit set. -
.symlink(old_name, new_name) ⇒ 0
Creates a symbolic link called new_name for the existing file old_name.
-
.symlink?(file_name) ⇒ Boolean
Returns
true
if the named file is a symbolic link. -
.truncate(file_name, integer) ⇒ 0
Truncates the file file_name to be at most integer bytes long.
-
.umask ⇒ Integer
Returns the current umask value for this process.
-
.unlink(file_name, ...) ⇒ Integer
Alias for .delete.
-
.utime(atime, mtime, file_name,...) ⇒ Integer
Sets the access and modification times of each named file to the first two arguments.
-
.world_readable?(file_name) ⇒ Fixnum?
If file_name is readable by others, returns an integer representing the file permission bits of file_name.
-
.world_writable?(file_name) ⇒ Fixnum?
If file_name is writable by others, returns an integer representing the file permission bits of file_name.
-
.writable?(file_name) ⇒ Boolean
Returns
true
if the named file is writable by the effective user id of this process. -
.writable_real?(file_name) ⇒ Boolean
Returns
true
if the named file is writable by the real user id of this process. -
.zero?(file_name) ⇒ Boolean
Returns
true
if the named file exists and has a zero size.
::IO - Inherited
.binread | Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). |
.binwrite | Same as IO.write except opening the file in binary mode and ASCII-8BIT encoding (“wb:ASCII-8BIT”). |
.copy_stream |
|
.for_fd | Synonym for IO.new. |
.foreach | Executes the block for every line in the named I/O port, where lines are separated by sep. |
.open | Alias for .open. |
.pipe | ::IO.pipe(…) {|read_io, write_io| … } |
.popen | Runs the specified command as a subprocess; the subprocess's standard input and output will be connected to the returned ::IO object. |
.read | Opens the file, optionally seeks to the given |
.readlines | Reads the entire file specified by name as individual lines, and returns those lines in an array. |
.select | Alias for Kernel.select. |
.sysopen | Opens the given path, returning the underlying file descriptor as a ::Fixnum. |
.try_convert | Try to convert obj into an ::IO, using to_io method. |
.write | Opens the file, optionally seeks to the given offset, writes string, then returns the length written. |
Instance Attribute Summary
::IO - Inherited
#autoclose= | Sets auto-close flag. |
#autoclose? | Returns |
#close_on_exec= | Sets a close-on-exec flag. |
#close_on_exec? | Returns |
#lineno | Returns the current line number in ios. |
#lineno= | Manually sets the current line number to the given value. |
#pos | Returns the current offset (in bytes) of ios. |
#pos= | Seeks to the given position (in bytes) in ios. |
#sync | Returns the current “sync mode'' of ios. |
#sync= | Sets the “sync mode'' to |
#binmode | Puts ios into binary mode. |
#binmode? | Returns |
#closed? | Returns |
#eof | Returns true if ios is at end of file that means there are no more data to read. |
#eof? | Alias for IO#eof. |
#isatty | Alias for IO#tty?. |
#tell | Alias for IO#pos. |
#tty? | Returns |
::Enumerable - Included
Instance Method Summary
-
#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).
-
#lstat ⇒ stat
Same as IO#stat, but does not follow the last symbolic link.
-
#mtime ⇒ Time
Returns the modification time for file.
-
#path ⇒ File
(also: #to_path)
Returns the pathname used to create file as a string.
-
#size ⇒ Integer
Returns the size of file in bytes.
-
#to_path ⇒ File
Alias for #path.
-
#truncate(integer) ⇒ 0
Truncates file to at most integer bytes.
::IO - Inherited
#<< | ::String Output—Writes obj to ios. |
#advise | Announce an intention to access data from the current file in a specific pattern. |
#bytes | This is a deprecated alias for |
#chars | This is a deprecated alias for |
#close | Closes ios and flushes any pending writes to the operating system. |
#close_read | Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). |
#close_write | Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). |
#codepoints | This is a deprecated alias for |
#each | ios.each_line(sep=$/) {|line| block } -> ios. |
#each_byte | Calls the given block once for each byte (0..255) in ios, passing the byte as an argument. |
#each_char | Calls the given block once for each character in ios, passing the character as an argument. |
#each_codepoint | Passes the ::Integer ordinal of each character in ios, passing the codepoint as an argument. |
#each_line | Alias for IO#each. |
#external_encoding | Returns the ::Encoding object that represents the encoding of the file. |
#fcntl | Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams. |
#fdatasync | Immediately writes all buffered data in ios to disk. |
#fileno | Alias for IO#to_i. |
#flush | Flushes any buffered data within ios to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well). |
#fsync | Immediately writes all buffered data in ios to disk. |
#getbyte | Gets the next 8-bit byte (0..255) from ios. |
#getc | Reads a one-character string from ios. |
#gets | Reads the next “line'' from the I/O stream; lines are separated by sep. |
#initialize | Returns a new ::IO object (a stream) for the given integer file descriptor |
#inspect | Return a string describing this ::IO object. |
#internal_encoding | Returns the ::Encoding of the internal string if conversion is specified. |
#ioctl | Provides a mechanism for issuing low-level commands to control or query I/O devices. |
#lines | This is a deprecated alias for |
#pid | Returns the process ID of a child process associated with ios. |
Writes the given object(s) to ios. |
|
#printf | Formats and writes to ios, converting parameters under control of the format string. |
#putc | If obj is ::Numeric, write the character whose code is the least-significant byte of obj, otherwise write the first byte of the string representation of obj to ios. |
#puts | Writes the given object(s) to ios as with IO#print. |
#read | Reads length bytes from the I/O stream. |
#read_nonblock | Reads at most maxlen bytes from ios using the read(2) system call after O_NONBLOCK is set for the underlying file descriptor. |
#readbyte | Reads a byte as with IO#getbyte, but raises an ::EOFError on end of file. |
#readchar | Reads a one-character string from ios. |
#readline | Reads a line as with IO#gets, but raises an ::EOFError on end of file. |
#readlines | Reads all of the lines in ios, and returns them in anArray. |
#readpartial | Reads at most maxlen bytes from the I/O stream. |
#reopen | Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path. |
#rewind | Positions ios to the beginning of input, resetting |
#seek | Seeks to a given offset anInteger in the stream according to the value of whence: |
#set_encoding | If single argument is specified, read string from io is tagged with the encoding specified. |
#stat | Returns status information for ios as an object of type Stat. |
#sysread | Reads maxlen bytes from ios using a low-level read and returns them as a string. |
#sysseek | Seeks to a given offset in the stream according to the value of whence (see IO#seek for values of whence). |
#syswrite | Writes the given string to ios using a low-level write. |
#to_i | Returns an integer representing the numeric file descriptor for ios. |
#to_io | Returns ios. |
#ungetbyte | Pushes back bytes (passed as a parameter) onto ios, such that a subsequent buffered read will return it. |
#ungetc | Pushes back one character (passed as a parameter) onto ios, such that a subsequent buffered character read will return it. |
#write | Writes the given string to ios. |
#write_nonblock | Writes the given string to ios using the write(2) system call after O_NONBLOCK is set for the underlying file descriptor. |
::Enumerable - Included
#chunk | Enumerates over the items, chunking them together based on the return value of the block. |
#collect | Alias for Enumerable#map. |
#collect_concat | Alias for Enumerable#flat_map. |
#count | Returns the number of items in |
#cycle | Calls block for each element of enum repeatedly n times or forever if none or |
#detect | Alias for Enumerable#find. |
#drop | Drops first n elements from enum, and returns rest elements in an array. |
#drop_while | Drops elements up to, but not including, the first element for which the block returns |
#each_cons | Iterates the given block for each array of consecutive <n> elements. |
#each_entry | Calls block once for each element in |
#each_slice | Iterates the given block for each slice of <n> elements. |
#each_with_index | Calls block with two arguments, the item and its index, for each item in enum. |
#each_with_object | Iterates the given block for each element with an arbitrary object given, and returns the initially given object. |
#entries | Alias for Enumerable#to_a. |
#find | Passes each entry in enum to block. |
#find_all | Alias for Enumerable#select. |
#find_index | Compares each entry in enum with value or passes to block. |
#first | Returns the first element, or the first |
#flat_map | Returns a new array with the concatenated results of running block once for every element in enum. |
#grep | Returns an array of every element in enum for which |
#group_by | Groups the collection by result of the block. |
#include? | Alias for Enumerable#member?. |
#inject | Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. |
#lazy | Returns a lazy enumerator, whose methods map/collect, flat_map/collect_concat, select/find_all, reject, grep, zip, take, take_while, drop, and drop_while enumerate values only on an as-needed basis. |
#map | Returns a new array with the results of running block once for every element in enum. |
#max | Returns the object in enum with the maximum value. |
#max_by | Returns the object in enum that gives the maximum value from the given block. |
#member? | Returns |
#min | Returns the object in enum with the minimum value. |
#min_by | Returns the object in enum that gives the minimum value from the given block. |
#minmax | Returns two elements array which contains the minimum and the maximum value in the enumerable. |
#minmax_by | Returns a two element array containing the objects in enum that correspond to the minimum and maximum values respectively from the given block. |
#partition | Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest. |
#reduce | Alias for Enumerable#inject. |
#reject | Returns an array for all elements of |
#reverse_each | Builds a temporary array and traverses that array in reverse order. |
#select | Returns an array containing all elements of |
#slice_after | Creates an enumerator for each chunked elements. |
#slice_before | Creates an enumerator for each chunked elements. |
#slice_when | Creates an enumerator for each chunked elements. |
#sort | Returns an array containing the items in enum sorted, either according to their own |
#sort_by | Sorts enum using a set of keys generated by mapping the values in enum through the given block. |
#take | Returns first n elements from enum. |
#take_while | Passes elements to the block until the block returns |
#to_a | Returns an array containing the items in enum. |
#to_h | Returns the result of interpreting enum as a list of |
#zip | Takes one element from enum and merges corresponding elements from each args. |
Constructor Details
.new(filename, mode="r" [, opt]) ⇒ File
.new(filename [, mode [, perm]] [, opt]) ⇒ File
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)
Class Attribute Details
.directory?(file_name) ⇒ Boolean
(readonly)
Alias for Dir.exist?.
Class Method Details
.absolute_path(file_name [, dir_string] ) ⇒ File
Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. If the given pathname starts with a “~
'' it is NOT expanded, it is treated as a normal directory name.
File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
.atime(file_name) ⇒ Time
.basename(file_name [, suffix] ) ⇒ base_name
Returns the last component of the filename given in file_name, which can be formed using both SEPARATOR and ALT_SEPARATOR as the separator when ALT_SEPARATOR is not nil
. If suffix is given and present at the end of file_name, it is removed. If suffix is “.*”, any extension will be removed.
File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
.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
.blockdev?(file_name) ⇒ Boolean
Returns true
if the named file is a block device.
file_name can be an ::IO object.
.chardev?(file_name) ⇒ Boolean
Returns true
if the named file is a character device.
file_name can be an ::IO object.
.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
.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")
.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
Also known as: .unlink
Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir.rmdir.
.dirname(file_name) ⇒ dir_name
Returns all components of the filename given in file_name except the last one. The filename can be formed using both SEPARATOR and ALT_SEPARATOR as the separator when ALT_SEPARATOR is not nil
.
File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
.executable?(file_name) ⇒ Boolean
Returns true
if the named file is executable by the effective user id of this process.
.executable_real?(file_name) ⇒ Boolean
Returns true
if the named file is executable by the real user id of this process.
.exist?(file_name) ⇒ Boolean
Return true
if the named file exists.
file_name can be an ::IO object.
“file exists” means that stat() or fstat() system call is successful.
.exists?(file_name) ⇒ Boolean
Deprecated method. Don't use.
.expand_path(file_name [, dir_string] ) ⇒ File
Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string
is given, in which case it will be used as the starting point. The given pathname may start with a “~
'', which expands to the process owner's home directory (the environment variable HOME
must be set correctly). “~
user'' expands to the named user's home directory.
File. ("~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
.
.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"
.file?(file) ⇒ Boolean
Returns true
if the named file
exists and is a regular file.
file
can be an ::IO object.
If the file
argument is a symbolic link, it will resolve the symbolic link and use the file referenced by the link.
.fnmatch(pattern, path, [flags]) ⇒ Boolean
.fnmatch?(pattern, path, [flags]) ⇒ Boolean
Also known as: .fnmatch?
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
.fnmatch(pattern, path, [flags]) ⇒ Boolean
.fnmatch?(pattern, path, [flags]) ⇒ Boolean
Boolean
.fnmatch?(pattern, path, [flags]) ⇒ Boolean
Alias for .fnmatch.
.ftype(file_name) ⇒ String
Identifies the type of the named file; the return string is one of “file
'', “directory
'', “characterSpecial
'', “blockSpecial
'', “fifo
'', “link
'', “socket
'', or “unknown
''.
File.ftype("testfile") #=> "file"
File.ftype("/dev/tty") #=> "characterSpecial"
File.ftype("/tmp/.X11-unix/X0") #=> "socket"
.grpowned?(file_name) ⇒ Boolean
Returns true
if the named file exists and the effective group id of the calling process is the owner of the file. Returns false
on Windows.
file_name can be an ::IO object.
.identical?(file_1, file_2) ⇒ Boolean
Returns true
if the named files are identical.
file_1 and file_2 can be an ::IO object.
open("a", "w") {}
p File.identical?("a", "a") #=> true
p File.identical?("a", "./a") #=> true
File.link("a", "b")
p File.identical?("a", "b") #=> true
File.symlink("a", "c")
p File.identical?("a", "c") #=> true
open("d", "w") {}
p File.identical?("a", "d") #=> false
.join(string, ...) ⇒ String
Returns a new string formed by joining the strings using SEPARATOR.
File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
.lchmod(mode_int, file_name, ...) ⇒ Integer
Equivalent to .chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). Often not available.
.lchown(owner_int, group_int, file_name,..) ⇒ Integer
Equivalent to .chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). Often not available. Returns number of files in the argument list.
.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"
.lstat(file_name) ⇒ stat
.mtime(file_name) ⇒ Time
With no associated block, open
is a synonym for .new. If the optional code block is given, it will be passed the opened file
as an argument and the File
object will automatically be closed when the block terminates. The value of the block will be returned from open
.
If a file is being created, its initial permissions may be set using the perm
parameter. See .new for further discussion.
See IO.new for a description of the mode
and opt
parameters.
.owned?(file_name) ⇒ Boolean
Returns true
if the named file exists and the effective used id of the calling process is the owner of the file.
file_name can be an ::IO object.
.path(path) ⇒ String
Returns the string representation of the path
File.path("/dev/null") #=> "/dev/null"
File.path(Pathname.new("/tmp")) #=> "/tmp"
.pipe?(file_name) ⇒ Boolean
Returns true
if the named file is a pipe.
file_name can be an ::IO object.
.readable?(file_name) ⇒ Boolean
Returns true
if the named file is readable by the effective user id of this process.
.readable_real?(file_name) ⇒ Boolean
Returns true
if the named file is readable by the real user id of this process.
.readlink(link_name) ⇒ File
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"
.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.
.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.
.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
.setgid?(file_name) ⇒ Boolean
Returns true
if the named file has the setgid bit set.
.setuid?(file_name) ⇒ Boolean
Returns true
if the named file has the setuid bit set.
.size(file_name) ⇒ Integer
Returns the size of file_name
.
file_name can be an ::IO object.
.size?(file_name) ⇒ Integer?
Returns nil
if file_name
doesn't exist or has zero size, the size of the file otherwise.
file_name can be an ::IO object.
.socket?(file_name) ⇒ Boolean
Returns true
if the named file is a socket.
file_name can be an ::IO object.
.split(file_name) ⇒ Array
.stat(file_name) ⇒ stat
Returns a ::File::Stat object for the named file (see ::File::Stat).
File.stat("testfile").mtime #=> Tue Apr 08 12:58:04 CDT 2003
.sticky?(file_name) ⇒ Boolean
Returns true
if the named file has the sticky bit set.
.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
.symlink?(file_name) ⇒ Boolean
Returns true
if the named file is a symbolic link.
.truncate(file_name, integer) ⇒ 0
Returns the current umask value for this process. If the optional argument is given, set the umask to that value and return the previous value. Umask values are subtracted from the default permissions, so a umask of 0222
would make a file read-only for everyone.
File.umask(0006) #=> 18
File.umask #=> 6
Alias for .delete.
.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.
.world_readable?(file_name) ⇒ Fixnum?
If file_name is readable by others, returns an integer representing the file permission bits of file_name. Returns nil
otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2)
.
file_name can be an ::IO object.
File.world_readable?("/etc/passwd") #=> 420
m = File.world_readable?("/etc/passwd")
sprintf("%o", m) #=> "644"
.world_writable?(file_name) ⇒ Fixnum?
If file_name is writable by others, returns an integer representing the file permission bits of file_name. Returns nil
otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2)
.
file_name can be an ::IO object.
File.world_writable?("/tmp") #=> 511
m = File.world_writable?("/tmp")
sprintf("%o", m) #=> "777"
.writable?(file_name) ⇒ Boolean
Returns true
if the named file is writable by the effective user id of this process.
.writable_real?(file_name) ⇒ Boolean
Returns true
if the named file is writable by the real user id of this process.
.zero?(file_name) ⇒ Boolean
Returns true
if the named file exists and has a zero size.
file_name can be an ::IO object.
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
#birthtime ⇒ Time
#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
#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)
#ctime ⇒ Time
#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
}
#lstat ⇒ stat
#mtime ⇒ Time
#path ⇒ File
#to_path ⇒ File
Also known as: #to_path
File
#to_path ⇒ File
#size ⇒ Integer
#path ⇒ File
#to_path ⇒ File
File
#to_path ⇒ File
Alias for #path.