2011-02-15 27 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); 
} 
相關問題