要求:
只能使用命令行,比較兩個文件夾的不同,包括文件的差異。
思考:
雖然linux下有diff。。。。還是用php吧,代碼改的方便,速度也很快,以下排除了.svn目錄的比較
文件要比較md5校驗和
思路:
1)把第一路徑作為標準路徑,列出第1個路徑中有的,第2個路徑中沒有的文件或文件夾,或者是不同的文件。
2)然后,列出第2個路徑中有的,第1個路徑中卻不存在的文件和文件夾。
調用示例:
php compare_folder.php /home/temp/2 /home/temp/55
//轉載自JAVAEYE
源碼:
<?php
/**
*工具文件
*目的在于遞歸比較兩個文件夾
*
*調用示例
*phpcompare_folder.php/home/temp/2/home/temp/55
*
*/
//參數確定
if(count($argv)>1)
$dir1=del_postfix($argv[1]);
else
$dir1='/';
if(count($argv)>2)
$dir2=del_postfix($argv[2]);
else
$dir2='/';
//檢查第一個路徑有,后者沒有或錯誤的方法。
process_compare($dir1,$dir2,0);
echo"===========================================================/n";
//檢查第2個路徑的多余文件夾或文件
process_compare($dir2,$dir1,1);
echo"allOK/n";
/**
*去除路徑末尾的/,并確保是絕對路徑
*
*@paramunknown_type$dir
*@returnunknown
*/
functiondel_postfix($dir)
{
if(!preg_match('#^/#',$dir)){
thrownewException('參數必須是絕對路徑');
}
$dir=preg_replace('#/$#','',$dir);
return$dir;
}
/**
*公用函數,會調用一個遞歸方法實現比較
*
*@paramstring$dir1作為標準的路徑
*@paramstring$dir2對比用的路徑
*@paramint$only_check_has為1表示不比較文件差異,為0表示還要比較文件的md5校驗和
*/
functionprocess_compare($dir1,$dir2,$only_check_has){
compare_file_folder($dir1,$dir1,$dir2,$only_check_has);
}
/**
*真實的函數,私有函數
*
*@paramstring$dir1路徑1,是標準
*@paramstring$base_dir1不變的參數路徑2
*@paramstring$base_dir2不變的待比較的路徑2
*@paramint$only_check_has為1表示不比較文件差異,為0表示還要比較文件的md5校驗和
*
*/
functioncompare_file_folder($dir1,$base_dir1,$base_dir2,$only_check_has=0){
if(is_dir($dir1)){
$handle=dir($dir1);
if($dh=opendir($dir1)){
while($entry=$handle->read()){
if(($entry!=".")&&($entry!="..")&&($entry!=".svn")){
$new=$dir1."/".$entry;
//echo'compare:'.$new."/n";
$other=preg_replace('#^'.$base_dir1.'#',$base_dir2,$new);
if(is_dir($new)){
//比較
if(!is_dir($other)){
echo'!!notfounddirection:'.$other.'('.$new.")/n";
}
compare_file_folder($new,$base_dir1,$base_dir2,$only_check_has);
}else{//如果1是文件,則2也應該是文件
if(!is_file($other)){
echo'!!notfoundfile:'.$other.'('.$new.")/n";
}elseif($only_check_has==0&&(md5_file($other)!=md5_file($new))){
echo'!!filemd5error:'.$other.'('.$new.")/n";
}
}
}
}
closedir($dh);
}
}
}
?>
新聞熱點
疑難解答