- /*
- 文件名: 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;
- }