linuxC遞迴刪除某個非空資料夾
做usbcopy程式的時候,發現linux下除了刪除命令 rm -fr 目錄名 刪除某個非空資料夾,沒有直接可以刪除非空目錄的函式。
只好自己寫個函式實現遞迴刪除。(經有限次測試)
int deletedir(char *fp)
{
int n = 0;
DIR *s=NULL;
char sname[256];
struct dirent *p=NULL;
if((s=opendir(fp))!=NULL)
{
while((p=readdir(s))!=NULL)
{
if(strcmp(p->d_name,"..") != 0 && strcmp(p->d_name,".") != 0)
{
strcpy(sname,"\0");
strcat(sname,fp);
strcat(sname,"/");
strcat(sname,p->d_name);
if(p->d_type==4) /*遞迴刪除目錄*/
deletedir(sname);
rmdir(sname);
if(p->d_type==8)
remove(sname);
}
}
rmdir(fp);
}
closedir(s);
return 0;
}