2011-02-15 99 views
0

我正在寻找一种方法来比较2个目录,以查看两个文件是否都存在。我想要做的是删除其中一个目录中的文件(如果它们都存在)。使用ASP或PHP检查文件是否存在于2个目录中

我既可以使用ASPPHP

例子:

/devices/1001 
/devices/1002 
/devices/1003 
/devices/1004 
/devices/1005 

/disabled/1001 
/disabled/1002 
/disabled/1003 

如此以来1001, 1002, 1003/残疾/存在,我想从/设备/删除它们,只留下1004, 1005/设备/

+0

请问您目前的代码不能正常工作?如果不是为什么?或者你正在寻找更好的方法来做到这一点? – Jacob 2011-02-15 04:36:30

+0

我正在使用的测试中,设备中的20个文件都存在desabled中,2个设备中不存在disbaled,我的代码告诉我他们都不存在。 – WrightsCS 2011-02-15 04:44:28

回答

5

使用scandir()获取文件名的每个目录的数组,然后使用array_intersect()地发现,存在于任何给定其他参数的第一个数组的元素。

http://au.php.net/manual/en/function.scandir.php

http://au.php.net/manual/en/function.array-intersect.php

<?php 
$devices = scandir('/i/auth/devices/'); 
$disabled = scandir('/i/auth/disabled/'); 

foreach(array_intersect($devices, $disabled) as $file) { 
    if ($file == '.' || $file == '..') 
     continue; 
    unlink('/i/auth/devices/'.$file); 
} 

应用为包括检查目录是有效的函数:

<?php 
function removeDuplicateFiles($removeFrom, $compareTo) { 
    $removeFromDir = realpath($removeFrom); 
    if ($removeFromDir === false) 
     die("Invalid remove from directory: $removeFrom"); 

    $compareToDir = realpath($compareTo); 
    if ($compareToDir === false) 
     die("Invalid compare to directory: $compareTo"); 

    $devices = scandir($removeFromDir); 
    $disabled = scandir($compareToDir); 

    foreach(array_intersect($devices, $disabled) as $file) { 
     if ($file == '.' || $file == '..') 
      continue; 
     unlink($removeFromDir.DIRECTORY_SEPARATOR.$file); 
    } 
} 

removeDuplicateFiles('/i/auth/devices/', '/i/auth/disabled/'); 
1

这对PHP来说非常简单 - 在这个例子中,我们设置了两个基本目录和文件名......这可能很容易成为foreach()循环中的一个数组。然后我们检查两个目录,看它是否确实存在于每个目录中。如果是这样,我们从第一个删除。这可以很容易地修改为从第二个删除。

见下文:

<?php 

$filename = 'foo.html'; 
$dir1 = '/var/www/'; 
$dir2 = '/var/etc/'; 
if(file_exists($dir1 . $filename) && file_exists($dir2 . $filename)){ 
    unlink($dir1 . $filename); 
} 
+0

如果我不知道$ filename的名字怎么办?有很多随机文件生成,所以文件名首先是不知道的。我需要它遍历两个目录并比较文件名。 – WrightsCS 2011-02-15 04:47:28

0

在PHP中,用这个文件是否存在检查....它会返回真或假...

file_exists(相对file_path)

0

对于设备中的每个文件,使用禁用的路径和来自设备的文件名来检查它是否存在于禁用中。

<% 

    Set fso = server.createobject("Scripting.FileSystemObject") 

    Set devices = fso.getfolder(server.mappath("/i/auth/devices/")) 
    Set disabledpath = server.mappath("/i/auth/disabled/") 

    For each devicesfile in devices.files 
     if directory.fileExists(disablepath & devicesfile.name) Then 

      Response.Write " YES " 
      Response.write directoryfile.name & "<br>" 

     Else 

      Response.Write " NO " 
      Response.write directoryfile.name & "<br>" 

     End if 
    Next  

%> 
1
if ($handle = opendir('/disabled/')) { 
    while (false !== ($file = readdir($handle))) { 
     if ($file != "." && $file != "..") { 
      unlink('/devices/' . $file);    
     } 
    } 
    closedir($handle); 
} 
相关问题