Класс File править

ftools adds several (class, not instance) methods to the File class, for copying, moving, deleting, installing, and comparing files, as well as creating a directory path. See the File class for details. FileUtils contains all or nearly all the same functionality and more, and is a recommended option over ftools When you

 require 'ftools'

then the File class aquires some utility methods for copying, moving, and deleting files, and more. See the method descriptions below, and consider using FileUtils as it is more comprehensive.


Примеси

Windows::DeviceIO (CTL_CODE, DeviceIoControl, FSCTL_SET_COMPRESSION, FSCTL_SET_SPARSE),

Windows::Error (FormatMessage, FormatMessageW, GetLastError, SetErrorMode, SetLastError, SetLastErrorEx, get_last_error),

Windows::File (CopyFile, CopyFileEx, CreateFile, CreateHardLink, DecryptFile, DeleteFile, EncryptFile, GetBinaryType, GetFileAttributes, GetFileAttributesEx, GetFileSize, GetFileSizeEx, GetFileType, GetFullPathName, GetLongPathName, GetShortPathName, LockFile, LockFileEx, ReadFile, ReadFileEx, SetFileAttributes, UnlockFile, UnlockFileEx, WriteFile, WriteFileEx),

Windows::Limits (),

Windows::Security (AddAce, CopySid, GetAce, GetFileSecurity, GetLengthSid, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, InitializeAcl, InitializeSecurityDescriptor, LookupAccountName, LookupAccountSid, SetFileSecurity, SetSecurityDescriptorDacl)

Константы

ADD, ALT_SEPARATOR, ARCHIVE, BUFSIZE, CHANGE, COMPRESSED, CONTENT_INDEXED, FULL, HIDDEN, INDEXED, MAX_PATH, NORMAL, OFFLINE, PATH_SEPARATOR, READ, READONLY, SECURITY_RIGHTS, SEPARATOR, SYSTEM, Separator, TEMPORARY, VERSION

Методы класса

archive?, atime, attributes, basename, blksize, blockdev?, catname, chardev?, chmod, chown, compare, compressed?, copy, ctime, decrypt, delete, directory?, dirname, encrypted?, encrypt, executable?, executable_real?, exist?, exists?, expand_path, extname, file?, fnmatch?, fnmatch, ftype, get_permissions, grpowned?, hidden?, identical?, indexed?, install, join, lchmod, lchown, link, long_path, lstat, makedirs, move, mtime, new, normal?, offline?, owned?, pipe?, readable?, readable_real?, readlink, readonly?, remove_attributes, rename, reparse_point?, safe_unlink, securities, set_attributes, set_permissions, setgid?, setuid?, short_path, size?, size, socket?, sparse?, split, stat, sticky?, symlink?, symlink, syscopy, system?, temporary?, truncate, umask, unlink, utime, writable?, writable_real?, zero?

Методы объекта

archive=, atime, chmod, chown, compressed=, content_indexed=, ctime, flock, hidden=, indexed=, lstat, mtime, normal=, o_chmod, offline=, path, readonly=, sparse=, stat, system=, temporary=, truncate

File::archive? править


 File::archive?(file)

Возвращает true если файл или директория являются архивом. Приложения используют этот атрибут для маркировки файлов для резервного копирования или удаления.

File::atime править


 File.atime(file_name)  =>  time

Возвращает последнее время доступа для указанного файла как объект Time.

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

File::attributes править


 File::attributes(file)

Возвращает массив строк с указанием атрибутов для этого файла. Возможные значения: архив сжатый каталог зашифрованный скрытый индексированный нормальный автономный только чтнение точка повторной обработки разреженная система временная Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, используя метод: File::basename

File::blksize править


 File::blksize(file)

Возвращает блок файловой системы. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, используя метод: File::blockdev?

File::catname править


 File::catname(from, to)

If to is a valid directory, from will be appended to to, adding and escaping backslashes as necessary. Otherwise, to will be returned. Useful for appending from to to only if the filename was not specified in to. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, используя метод: : File::chardev?

File::chmod=== править


 File::chmod(mode, *files)

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

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

File::chown править


 File.chown(owner_int, group_int, file_name,... ) -> integer

Changes the owner and group of the named file(s) to the given numeric owner and group id's. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file's group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Returns the number of files processed.

  File.chown(nil, 100, "testfile")

File::compare править


 File::compare(from, to, verbose = false)

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

File::compressed? править


 File::compressed?(file)

Returns true if the file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.

File::copy править


 File::copy(from, to, verbose = false)

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

File::ctime править


 File.ctime(file_name)  => time

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

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

File::decrypt править


 File::decrypt(file)

Decrypts an encrypted file or directory. The caller must have the FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access rights. Requires exclusive access to the file being decrypted, and will fail if another process is using the file. If the file is not encrypted an error is NOT raised. Windows 2000 or later only.

File::delete править


 File.delete(file_name, ...)  => integer
 File.unlink(file_name, ...)  => integer

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

File::directory? править


 File.directory?(file_name)   =>  true or false

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

  File.directory?(".")

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::dirname, File::dirname

File::encrypt править


 File::encrypt(file)

Encrypts a file or directory. All data streams in a file are encrypted. All new files created in an encrypted directory are encrypted. The caller must have the FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access rights. Requires exclusive access to the file being encrypted, and will fail if another process is using the file. If the file is compressed, EncryptFile will decompress the file before encrypting it. Windows 2000 or later only.

File::encrypted? править


 File::encrypted?(file)

Returns true if the file or directory is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories.

File::executable? править


 File.executable?(file_name)   => true or false

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

File::executable_real? править


 File.executable_real?(file_name)   => true or false

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

File::exist? править


 File.exist?(file_name)    =>  true or false
 File.exists?(file_name)   =>  true or false    (obsolete)

Return true if the named file exist

File::exists? править


 File.exist?(file_name)    =>  true or false
 File.exists?(file_name)   =>  true or false    (obsolete)

Return true if the named file exists. Метод возвращает true , если указанный файл file_name существует

File::expand_path править


 File.expand_path(file_name [, dir_string] ) -> abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a ``~, which expands to the process owner's home directory (the environment variable HOME must be set correctly). ``~user expands to the named user's home directory.

  File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"
  File.expand_path("../../bin", "/tmp/x")   #=> "/bin"

File::extname править


 File.extname(path) -> string

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

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

File::file? править


 File.file?(file_name)   => true or false

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

File::fnmatch править


 File.fnmatch( pattern, path, [flags] ) => (true or false)
 File.fnmatch?( pattern, path, [flags] ) => (true or false)

Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:

Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp. Matches any one character. Equivalent to /.{1}/ in regexp. Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).

Escapes the next metacharacter.

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

  File.fnmatch('cat',       'cat')        #=> true
  File.fnmatch('cat',       'category')   #=> false
  File.fnmatch('c{at,ub}s', 'cats')       #=> false
  File.fnmatch('c{at,ub}s', 'cubs')       #=> false
  File.fnmatch('c{at,ub}s', 'cat')        #=> false
  File.fnmatch('c?t',    'cat')                       #=> true
  File.fnmatch('c\?t',   'cat')                       #=> false
  File.fnmatch('c??t',   'cat')                       #=> false
  File.fnmatch('c*',     'cats')                      #=> true
  File.fnmatch('c/ * FIXME * /t', 'c/a/b/c/t')                 #=> true
  File.fnmatch('c*t',    'cat')                       #=> true
  File.fnmatch('c\at',   'cat')                       #=> true
  File.fnmatch('c\at',   'cat', File::FNM_NOESCAPE)   #=> false
  File.fnmatch('a?b',    'a/b')                       #=> true
  File.fnmatch('a?b',    'a/b', File::FNM_PATHNAME)   #=> false
  File.fnmatch('*',   '.profile')                            #=> false
  File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)        #=> true
  File.fnmatch('*',   'dave/.profile')                       #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_DOTMATCH)   #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_PATHNAME)   #=> false
  File.fnmatch('* / FIXME *', 'dave/.profile', File::FNM_PATHNAME)   #=> false
  STRICT = File::FNM_PATHNAME | File::FNM_DOTMATCH
  File.fnmatch('* / FIXME *', 'dave/.profile', STRICT)               #=> true

File::fnmatch? править


 File.fnmatch( pattern, path, [flags] ) => (true or false)
 File.fnmatch?( pattern, path, [flags] ) => (true or false)

Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:

Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp. Matches any one character. Equivalent to /.{1}/ in regexp. Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).

Escapes the next metacharacter.

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

  File.fnmatch('cat',       'cat')        #=> true
  File.fnmatch('cat',       'category')   #=> false
  File.fnmatch('c{at,ub}s', 'cats')       #=> false
  File.fnmatch('c{at,ub}s', 'cubs')       #=> false
  File.fnmatch('c{at,ub}s', 'cat')        #=> false
  File.fnmatch('c?t',    'cat')                       #=> true
  File.fnmatch('c\?t',   'cat')                       #=> false
  File.fnmatch('c??t',   'cat')                       #=> false
  File.fnmatch('c*',     'cats')                      #=> true
  File.fnmatch('c/ * FIXME * /t', 'c/a/b/c/t')                 #=> true
  File.fnmatch('c*t',    'cat')                       #=> true
  File.fnmatch('c\at',   'cat')                       #=> true
  File.fnmatch('c\at',   'cat', File::FNM_NOESCAPE)   #=> false
  File.fnmatch('a?b',    'a/b')                       #=> true
  File.fnmatch('a?b',    'a/b', File::FNM_PATHNAME)   #=> false
  File.fnmatch('*',   '.profile')                            #=> false
  File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)        #=> true
  File.fnmatch('*',   'dave/.profile')                       #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_DOTMATCH)   #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_PATHNAME)   #=> false
  File.fnmatch('* / FIXME *', 'dave/.profile', File::FNM_PATHNAME)   #=> false
  STRICT = File::FNM_PATHNAME | File::FNM_DOTMATCH
  File.fnmatch('* / FIXME *', 'dave/.profile', STRICT)               #=> true

File::ftype править


 File.ftype(file_name)   => string

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

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

File::get_permissions править


 File::get_permissions(file, host=nil)

Returns a hash describing the current file permissions for the given file. The account name is the key, and the value is an integer representing an or'd value that corresponds to the security permissions for that file. To get a human readable version of the permissions, pass the value to the +File.securities+ method.

File::grpowned? править


 File.grpowned?(file_name)   => true or false

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::hidden? править


 File::hidden?(file)

Returns true if the file or directory is hidden. It is not included in an ordinary directory listing.

File::identical? править


 File.identical?(file_1, file_2)   =>  true or false

Returns true if the named files are identical.

   open("a", "w") {}
   p File.identical?("a", "a")      #=> true
   p File.identical?("a", "./a")    #=> true
   File.link("a", "b")
   p File.identical?("a", "b")      #=> true
   File.symlink("a", "c")
   p File.identical?("a", "c")      #=> true
   open("d", "w") {}
   p File.identical?("a", "d")      #=> false

File::indexed? править


 File::indexed?(file)

Returns true if the file or directory is indexed by the content indexing service.

File::install править


 File::install(from, to, mode = nil, verbose = false)

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

File::join править


 File.join(string, ...) -> path

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

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

File::lchmod править


 File.lchmod(mode_int, file_name, ...)  => integer

Equivalent to File::chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). Often not available.

File::lchown править


 file.lchown(owner_int, group_int, file_name,..) => integer

Equivalent to File::chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). Often not available. Returns number of files in the argument list.

File::link править


 File.link(old_name, new_name)    => 0

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

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

File::long_path править


 File::long_path(file)

Returns file in long format. For example, if 'SOMEFI~1.TXT' was the argument provided, and the short representation for 'somefile.txt', then this method would return 'somefile.txt'. Note that certain file system optimizations may prevent this method from working as expected. In that case, you will get back the file name in 8.3 format. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::lstat, File::lstat===File::makedirs===


 File::makedirs(*dirs)

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

   File.makedirs '/usr/lib/ruby'

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

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

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

File::move править


 File::move(from, to, verbose = false)

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

File::mtime править


 File.mtime(file_name)  =>  time

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

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

File::new править


 File.new(filename, mode="r")            => file
 File.new(filename [, mode [, perm]])    => file

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

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

File::normal? править


 File::normal?(file)

Returns true if the file or directory has no other attributes set.

File::offline? править


 File::offline?(file)

Returns true if the data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.

File::owned? править


 File.owned?(file_name)   => true or false

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

File::pipe? править


 File.pipe?(file_name)   =>  true or false

Returns true if the named file is a pipe.

File::readable? править


 File.readable?(file_name)   => true or false

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

File::readable_real? править


 File.readable_real?(file_name)   => true or false

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

File::readlink править


 File.readlink(link_name) -> file_name

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

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

File::readonly? править


 File::readonly?(file)

Returns true if The file or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.

File::remove_attributes править


 File::remove_attributes(file, flags)

Removes the file attributes based on the given (numeric) flags.

File::rename править


 File.rename(old_name, new_name)   => 0

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

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

File::reparse_point? править


 File::reparse_point?(file)

Returns true if the file or directory has an associated reparse point. A reparse point is a collection of user defined data associated with a file or directory. For more on reparse points, search http://msdn.microsoft.com.

File::safe_unlink править


 File::safe_unlink(*files)

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

File::securities править


 File::securities(mask)

Returns an array of human-readable strings that correspond to the permission flags.

File::set_attributes править


 File::set_attributes(file, flags)

Sets the file attributes based on the given (numeric) flags. This does not remove existing attributes, it merely adds to them.

File::set_permissions править


 File::set_permissions(file, perms)

Sets the file permissions for the given file name. The 'permissions' argument is a hash with an account name as the key, and the various permission constants as possible values. The possible constant values are: FILE_READ_DATA FILE_WRITE_DATA FILE_APPEND_DATA FILE_READ_EA FILE_WRITE_EA FILE_EXECUTE FILE_DELETE_CHILD FILE_READ_ATTRIBUTES FILE_WRITE_ATTRIBUTES STANDARD_RIGHTS_ALL FULL READ ADD CHANGE DELETE READ_CONTROL WRITE_DAC WRITE_OWNER SYNCHRONIZE STANDARD_RIGHTS_REQUIRED STANDARD_RIGHTS_READ STANDARD_RIGHTS_WRITE STANDARD_RIGHTS_EXECUTE STANDARD_RIGHTS_ALL SPECIFIC_RIGHTS_ALL ACCESS_SYSTEM_SECURITY MAXIMUM_ALLOWED GENERIC_READ GENERIC_WRITE GENERIC_EXECUTE GENERIC_ALL

File::setgid? править


 File.setgid?(file_name)   =>  true or false

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

File::setuid? править


 File.setuid?(file_name)   =>  true or false

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

File::short_path править


 File::short_path(file)

Returns 'file_name' in 8.3 format. For example, 'c:\documentation.doc' would be returned as 'c:\docume~1.doc'. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::size?, File::size, File::blksize, File::size===File::size?===


 File.file?(file_name)   => integer  or  nil

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

File::socket? править


 File.socket?(file_name)   =>  true or false

Returns true if the named file is a socket.

File::sparse? править


 File::sparse?(file)

Returns true if the file is a sparse file. A sparse file is a file in which much of the data is zeros, typically image files. See http://msdn.microsoft.com for more details. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::split, File::splitБолее одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::lstat, File::stat, File::lstat, File::stat===File::sticky?===


 File.sticky?(file_name)   =>  true or false

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

File::symlink править


 File.symlink(old_name, new_name)   => 0

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

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

File::symlink? править


 File.symlink?(file_name)   =>  true or false

Returns true if the named file is a symbolic link.

File::syscopy править


 File::syscopy(from, to)

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

File::system? править


 File::system?(file)

Returns true if the file or directory is part of the operating system or is used exclusively by the operating system.

File::temporary? править


 File::temporary?(file)

Returns true if the file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.

File::truncate править


 File.truncate(file_name, integer)  => 0

Truncates the file file_name to be at most integer bytes long. Not available on all platforms.

  f = File.new("out", "w")
  f.write("1234567890")     #=> 10
  f.close                   #=> nil
  File.truncate("out", 5)   #=> 0
  File.size("out")          #=> 5

File::umask править


 File.umask()          => integer
 File.umask(integer)   => integer

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

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

File::unlink править


 File.delete(file_name, ...)  => integer
 File.unlink(file_name, ...)  => integer

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

File::utime править


 File.utime(atime, mtime, file_name,...)   =>  integer

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

File::writable? править


 File.writable?(file_name)   => true or false

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

File::writable_real? править


 File.writable_real?(file_name)   => true or false

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

File::zero? править


 File.zero?(file_name)   => true or false

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

File#archive= править


 archive=(bool)

Sets whether or not the file is an archive file.

File#atime править


 file.atime    => time

Returns the last access time (a Time object)

for file, or epoch if file has not been accessed.
  File.new("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969

File#chmod править


 file.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

(еще известен как o_chmod)

File#chown править


 file.chown(owner_int, group_int )   => 0

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

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

File#compressed= править


 compressed=(bool)

Sets whether or not the file is a compressed file.

File#content_indexed= править


 content_indexed=(bool)

Alias for #indexed=

File#ctime править


 file.ctime -> time

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

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

File#flock править


 file.flock (locking_constant ) =>  0 or 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:

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

File#hidden= править


 hidden=(bool)

Sets the hidden attribute to true or false. Setting this attribute to true means that the file is not included in an ordinary directory listing.

File#indexed= править


 indexed=(bool)

Sets the 'indexed' attribute to true or false. Setting this to false means that the file will not be indexed by the content indexing service.

(еще известен как content_indexed=)

File#lstat править


 file.lstat   =>  stat

Same as IO#stat, but does not follow the last symbolic link. Instead, reports on the link itself.

  File.symlink("testfile", "link2test")   #=> 0
  File.stat("testfile").size              #=> 66
  f = File.new("link2test")
  f.lstat.size                            #=> 8
  f.stat.size                             #=> 66

File#mtime править


 file.mtime -> time

Returns the modification time for file.

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

File#normal= править


 normal=(bool)

Sets the normal attribute. Note that only 'true' is a valid argument, which has the effect of removing most other attributes. Attempting to pass any value except true will raise an ArgumentError.

File#o_chmod править


 o_chmod(p1)

Alias for #chmod

File#offline= править


 offline=(bool)

Sets whether or not a file is online or not. Setting this to false means that the data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.

File#path править


 file.path -> filename

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

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

File#readonly= править


 readonly=(bool)

Sets the readonly attribute. If set to true the the file or directory is readonly. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.

File#sparse= править


 sparse=(bool)

Sets the file to a sparse (usually image) file. Note that you cannot remove the sparse property from a file.

File#stat править


 stat()

Instance methods

File#system= править


 system=(bool)

Set whether or not the file is a system file. A system file is a file that is part of the operating system or is used exclusively by it.

File#temporary= править


 temporary=(bool)

Sets whether or not the file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.

File#truncate править


 file.truncate(integer)    => 0

Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.

  f = File.new("out", "w")
  f.syswrite("1234567890")   #=> 10
  f.truncate(5)              #=> 0
  f.close()                  #=> nil
  File.size("out")           #=> 5