Programming Ruby

The Pragmatic Programmer's Guide

Previous < Contents ^
Next >

class File
Parent: IO
Version: 1.6

Index:

atime basename chmod chown ctime delete dirname expand_path ftype join link lstat mtime new open readlink rename size split stat symlink truncate umask unlink utime atime chmod chown ctime flock lstat mtime path truncate


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

In this section, 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 (or search, if a directory) the file:

Owner Group Other
r w x r w x r w x
4 2 1 4 2 1 4 2 1

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.

On non-Posix operating systems, there may be only the ability to make a file read-only or not. 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.
mixins
FileTest: blockdev?, chardev?, directory?, executable?, executable_real?, exist?, exists?, file?, grpowned?, owned?, pipe?, readable?, readable_real?, setgid?, setuid?, size, size?, socket?, sticky?, symlink?, writable?, writable_real?, zero?

Path separator constants (platform-specific)

ALT_SEPARATOR Alternate path separator.
PATH_SEPARATOR Character that separates filenames in a search path (such as ``:'' or ``;'').
SEPARATOR Character that separates directory components in a filename (such as ``\'' or ``/'').
Separator Alias for SEPARATOR.

Open-mode constants

APPEND Open the file in append mode; all writes will occur at end of file.
CREAT Create the file on open if it does not exist.
EXCL When used with CREAT, open will fail if the file exists.
NOCTTY When opening a terminal device (see IO#isatty on page 331), do not allow it to become the controlling terminal.
NONBLOCK Open the file in nonblocking mode.
RDONLY Open for reading only.
RDWR Open for reading and writing.
TRUNC Open the file and truncate it to zero length if the file exists.
WRONLY Open for writing only.

class methods
atime File.atime( fileName ) -> aTime

Returns the last access time for the named file.

File.atime("testfile") » Sun Jun 09 00:09:52 CDT 2002

basename File.basename( fileName [, aSuffix ] ) -> aNewString

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

File.basename("/home/gumby/work/ruby.rb") » "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb") » "ruby"

chmod File.chmod( aModeInt [, fileName ]+ ) -> anInteger

Changes permission bits on the named file(s) to the bit pattern represented by aModeInt. 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 File.chown( anOwnerInt, aGroupInt [, fileName ]+ ) -> anInteger

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.ctime( fileName ) -> aTime

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") » Sun Jun 09 00:17:17 CDT 2002

delete File.delete( [ fileName ]+ ) -> aFixnum

Deletes the named file(s). Returns the number of files processed. See also Dir.rmdir .

File.new("testrm", "w+").close » nil
File.delete("testrm") » 1

dirname File.dirname( fileName ) -> fileName

Returns all components of the filename given in fileName 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"

expand_path File.expand_path( fileName [, aDirString ] ) -> fileName

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless aDirString 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"

ftype File.ftype( fileName ) -> fileType

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

File.ftype("testfile") » "file"
File.ftype("/dev/tty") » "characterSpecial"
File.ftype("/tmp/.X11-unix/X0") » "socket"

join File.join( [ aString ]+ ) -> fileName

Returns a new string formed by joining the strings using File::SEPARATOR (see Table 22.2 on page 304).

File.join("usr", "mail", "gumby") » "usr/mail/gumby"

link File.link( anOldName, aNewName ) -> 0

Creates a new name for an existing file using a hard link. Will not overwrite aNewName 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.lstat( fileName ) -> aStat

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
File.lstat("link2test").size » 8
File.stat("link2test").size » 66

mtime File.mtime( fileName ) -> aTime

Returns the modification time for the named file.

File.mtime("testfile") » Sun Nov 25 23:48:26 CST 2001

new File.new( fileName, aModeString="r" ) -> file
File.new( fileName [, aModeNum [ aPermNum ] ] ) -> file
Opens the file named by fileName according to aModeString (default is ``r'') and returns a new File object. See Table 22.5 on page 326 for a description of aModeString. The file mode may optionally be specified as a Fixnum by or-ing together the flags described in Table 22.3 on page 305. Optional permission bits may be given in aPermNum. These mode and permission bits are platform dependent; on Unix systems, see open(2) for details.

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

open File.open( fileName, aModeString="r" ) -> file
File.open( fileName [, aModeNum [ aPermNum ] ] ) -> file
File.open( fileName, aModeString="r" ) {| file | block } -> nil
File.open( fileName [, aModeNum [ aPermNum ] ] ) {| file | block } -> nil

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 will automatically be closed when the block terminates. In this instance, File.open returns nil.

readlink File.readlink( fileName ) -> fileName

Returns the given symbolic link as a string. Not available on all platforms.

File.symlink("testfile", "link2test") » 0
File.readlink("link2test") » "testfile"

rename File.rename( anOldName, aNewName ) -> 0

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

File.rename("afile", "afile.bak") » 0

size File.size( fileName ) -> anInteger

Returns the size of the file in bytes.

File.size("testfile") » 66

split File.split( fileName ) -> anArray

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

stat File.stat( fileName ) -> aStat

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

File.stat("testfile").mtime » Sun Nov 25 23:48:26 CST 2001

symlink File.symlink( anOldName, aNewName ) -> 0 or nil

Creates a symbolic link called aNewName for the existing file anOldName. Returns nil on all platforms that do not support symbolic links.

File.symlink("testfile", "link2test") » 0

truncate File.truncate( fileName, anInteger ) -> 0

Truncates the file fileName to be at most anInteger 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

umask File.umask( [ anInteger ] ) -> anInteger

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. See also the discussion of permissions on page 301.

File.umask(0006) » 18
File.umask » 6

unlink File.unlink( [ fileName ]+ ) -> anInteger

Synonym for File.delete . See also Dir.rmdir .

utime File.utime( anAccessTime, aModTime [, fileName ]+ ) -> aFixnum

Changes the access and modification times on a number of files. The times must be instances of class Time or integers representing the number of seconds since epoch. Returns the number of files processed. Not available on all platforms.

File.utime(0, 0, "testfile") » 1
File.mtime("testfile") » Wed Dec 31 18:00:00 CST 1969
File.utime(0, Time.now, "testfile") » 1
File.mtime("testfile") » Sun Jun 09 00:17:19 CDT 2002

Lock-mode constants

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.

instance methods
atime file.atime -> aTime

Returns the last access time for file, or epoch if file has not been accessed.

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

chmod file.chmod( aModeInt ) -> 0

Changes permission bits on file to the bit pattern represented by aModeInt. Actual effects are platform dependent; on Unix systems, see chmod(2) for details. See the discussion of permissions on page 301.

f = File.new("out", "w");
f.chmod(0644) » 0

chown file.chown( anOwnerInt, aGroupInt ) -> 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.

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

ctime file.ctime -> aTime

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 » Sun Jun 09 00:17:19 CDT 2002

flock file.flock ( aLockingConstant ) -> 0 or false

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

File.new("testfile").flock(File::LOCK_UN) » 0

lstat file.lstat -> aStat

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

mtime file.mtime -> aTime

Returns the modification time for file.

File.new("testfile").mtime » Sun Jun 09 00:17:19 CDT 2002

path file.path -> fileName

Returns the pathname used to create file as a string.

File.new("testfile").path » "testfile"

truncate file.truncate( anInteger ) -> 0

Truncates file to at most anInteger 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


Previous < Contents ^
Next >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/)).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.