Alle sabato 3 novembre 2007, Oscar Del ben ha scritto:
Hello, this is my first post here, so first i would like to thanks all
the people who works for this site.
Well, i'm trying to set up a little script that should delete all the
files in a given drectory; the system should work like this:
-I have the name and the path of file = "/Users.....file1"
-from file, i should get the directory (I've used File.dirname(file))
-from that directory, i should delete all files and sub directories
except from the given file (in this case, file1)
I'm making confusion when i try to iterare on the files and irectory in
that folder, and i'm scared to make test of deleting files in the system
If I understand correctly what you need to do, this should work.
file_name = File.basename(file_path)
dir = File.dirname(file_path)
Dir.foreach(dir) do |f|
if f == file_name or f == '.' or f == '..' then next
elsif File.directory?(f) then FileUtils.rm_rf(f)
else FileUtils.rm( f )
To test the script, you can replace FileUtils.rm_rf(f) and FileUtils.rm(f) respectively with
FileUtils.rm_rf( f, :noop => true, :verbose => true)
FileUtils.rm( f, :noop => true, :verbose => true)
With those arguments, FileUtils.rm and FileUtils.rm_rf don't actually delete the files (or directories), but print the operation that would be performed on screen, so you can check whether everything works. For more information on this, look at the ri documentation for FileUtils and FileUtils.rm.
I hope this helps