Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use File.delete to remove file

System:

Windows Server 2008
Ruby 192

in 'delete': Permission denied Errno:EACCES

the line: File.delete('filename.ext')

If you know any other method to delete the file bypassing this error I'm glad to distribute you some points :) I mean any help would be appreciated ;-p

I was suspecting that file wasn't closed but it is closed.

Source code:

Dir.foreach(FileUtils.pwd()) do |f|
  a[i] = f
  if a[i].end_with?('log')
    file = File.open(a[i])
    if file.ctime < TIME_TO_REMOVE_LOGS || file.mtime < TIME_TO_REMOVE_LOGS || File.size(a[i]) > MAX_FILE_SIZE
      puts a[i]
      puts file.ctime
      puts file.mtime

      # zipping the file
      orig = a[i]
      Zlib::GzipWriter.open('arch_log.gz') do |gz|
        gz.mtime = File.mtime(orig)
        gz.orig_name = orig
        gz.write IO.binread(orig)
      end
      file.close
    end
  end
  File.delete(a[i])
  i = i + 1
end
like image 757
Jackie Chan Avatar asked Feb 08 '12 05:02

Jackie Chan


People also ask

How can I delete a file that won't delete?

One is simply using the delete option, and the other one is deleting files permanently. When you can't delete a file normally, you can delete undeletable files Windows 10 by selecting the target file or folder and then press Shift + Delete keys on the keyboard for a try.

Why won't my computer let me delete files?

It's most likely because another program is currently trying to use the file. This can occur even if you don't see any programs running. When a file is open by another app or process, Windows 11/10 puts the file into a locked state, and you can't delete, modify, or move it to another location.

How do I force a file to delete?

Use Shift + Delete to Force Delete File/Folder. You can select the target file or folder and press Shift + Delete keyboard shortcut to delete the file/folder permanently. This file deletion method won't pass the Recycle Bin.


1 Answers

It's not closed. The file only gets closed sometimes depending on ctime. There's a lot wrong with your code but the main point is this: be safe with your files and use a block.

File.open(a[i]) do |file|
  # access file 
end
# now you don't need to wonder if it's closed.
File.delete(a[i])

Also give your variables better names.

like image 113
pguardiario Avatar answered Sep 19 '22 00:09

pguardiario