[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 196
  • Last Modified:

Delete all files in a directory

I'm using Perl 5 on a WINDOWS NT server. It doesnt seem to accept the deltree command and besides I would like a more methodical way of deleting files. I can use the del command but it is waiting for confirmation if I send it the "*" wildcard. But if I could get a list of the files in a directory and set them in an array, and then iterate through them one at a time, I think this would be a solid answer. But how do I get a diretory list into an array?
0
microfleet
Asked:
microfleet
  • 3
1 Solution
 
guadalupeCommented:
     #Open dir handle
      opendir(dir,$dir);


            @files=grep {!(/^\./) && !(-d "$dir/$_")} readdir(dir);
      

      #loop over files
      foreach $file (@files)
      {
            #del file - remember to refer to complete path by usuing $dir/$file
      }



      closedir (dir);
0
 
guadalupeCommented:
To delete the file you could use perls command togeather with the variables defined in the loop like this:

unlink("$dir/$file");
0
 
guadalupeCommented:
You could also use this but some how I would consider "delete *.*" a risky move:

if (chdir("D:/Scratch/temp2/temp"))
{
      unlink<*.*>;
}

Note that though you are in windows you should use unix style forward slashes to change dir.  Back slashes will merely cause the chdir to fail and nothing will be deleted.
0
 
microfleetAuthor Commented:
I actually figured out a way to get the files to delete. I discoved the opendir function in my book and then it was just a matter of using the WINDOWS del call. But I like your way better because it doesnt limit itself to WINDOWS systems. Thanks. I will be posting another question now that deals with removing the directory. I thought I had that settled but it seems that after I remove all the files, the directory gives me an access error.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now