/*
檔案名: rd.c
----------------------------------------------------
c中提供的對檔案夾操作的函數,隻能對空檔案夾進行
删除,這使很多初學者在編碼過程中産生許多困擾,我也
很不爽這件事情,是以編寫這個對非空檔案夾進行删除的
函數,僅供參考。
注意:本函數編寫以VC6為依據,其中關于檔案夾的操作函數
與标準c有所差別。如VC6中的findclose可能需要用c
中的closedir()來代替。
日期 程式員 變更記錄
2010.4.28 海總(掌門人号) 建立檔案,編寫函數
*/
#include <stdio.h>
#include <io.h>
#include <string.h>
#include <direct.h>
函數入口:檔案夾的絕對路徑
const char* dirPath
函數功能:删除該檔案夾,包括其中所有的檔案和檔案夾
傳回值: 0 删除
-1 路徑不對,或其它情況,沒有執行删除操作
int removeDir(const char* dirPath)
{
struct _finddata_t fb; //查找相同屬性檔案的存儲結構體
char path[250];
long handle;
int resultone;
int noFile; //對系統隐藏檔案的處理标記
noFile = 0;
handle = 0;
//制作路徑
strcpy(path,dirPath);
strcat (path,"/*");
handle = _findfirst(path,&fb);
//找到第一個比對的檔案
if (handle != 0)
{
//當可以繼續找到比對的檔案,繼續執行
while (0 == _findnext(handle,&fb))
{
//windows下,常有個系統檔案,名為“..”,對它不做處理
noFile = strcmp(fb.name,"..");
if (0 != noFile)
{
//制作完整路徑
memset(path,0,sizeof(path));
strcpy(path,dirPath);
strcat(path,"/");
strcat (path,fb.name);
//屬性值為16,則說明是檔案夾,疊代
if (fb.attrib == 16)
{
removeDir(path);
}
//非檔案夾的檔案,直接删除。對檔案屬性值的情況沒做詳細調查,可能還有其他情況。
else
remove(path);
}
}
//關閉檔案夾,隻有關閉了才能删除。找這個函數找了很久,标準c中用的是closedir
//經驗介紹:一般産生Handle的函數執行後,都要進行關閉的動作。
_findclose(handle);
}
//移除檔案夾
resultone = rmdir(dirPath);
return resultone;
}