Monday, January 4, 2010

Section 8.5. File Inquiries


Working with Files > File Inquiries




8.5. File Inquiries


You can make all kinds of inquires about files with File methods. These kinds of tests are often done before another file procedure is done. For example, the following command tests whether a file exists before opening it:

File::open("file.rb") if File::exists?( "file.rb" )


You can also test whether the file exists with exist? (singular), a synonym of exists?. Inquire whether the file is really a file with file?:

File.file?( "sonnet29.txt" ) # => true


Or find out if it is a directory with directory?:

# try it with a directory
File::directory?( "/usr/local/bin" ) # => true

# try it with a file...oops
File::directory?( "file.rb" ) # => false


Test if the file is readable with readable?, writable with writable?, and executable with executable?:

File.readable?( "sonnet_119.txt" ) # => true
File.writable?( "sonnet_119.txt" ) # => true
File.executable?( "sonnet_119.txt" ) # => false


You can find out if a file has a length of zero (0) with zero?:

system("touch chap.txt") # Create a zero-length file with a system command
File.zero?( "chap.txt" ) # => true


Get its size in bytes with size? or size:

File.size?( "sonnet_129.txt" ) # => 594
File.size( "sonnet_129.txt" ) # => 594


Finally, inquire about the type of a file with ftype:

File::ftype( "file.rb" ) # => "file"


The ftype method identifies the type of the file by returning one of the following: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.


Find out when a file was created, modified, or last accessed with ctime, mtime, and atime, respectively:

File::ctime( "file.rb" ) # => Wed Nov 08 10:06:37 -0700 2006
File::mtime( "file.rb" ) # => Wed Nov 08 10:44:44 -0700 2006
File::atime( "file.rb" ) # => Wed Nov 08 10:45:01 -0700 2006


 

 


No comments: