Files and Directories

You can also use the File class to manipulate files and directories on disk. Before attempting to perform some operation on a file, you must naturally make sure that the file exists. It might, after all, have been renamed or deleted after the program started—or the user may have incorrectly entered a file or directory name.

You can verify the existence of a file using the File.exist? method. This is one of several testing methods that are provided to the File class by the FileTest module. As far as the File.exist? method is concerned, a directory counts as a file, so you could use the following code to test for the presence of a C: drive (note that you must use double file separator "\" characters in strings, because a single "" will be treated as an escape character):

file_ops.rb

if File.exist?( "C:\" ) then
    puts( "Yup, you have a C:\ directory" )
else
    puts( "Eeek! Can't find the C:\ drive!" )
end

If you want to distinguish between a directory and a data file, use the directory? method:

def dirOrFile( aName )
    if File.directory?( aName ) then
        puts( "#{aName} is a directory" )
    else
        puts( "#{aName} is a file" )
    end
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.149