再帰的に呼び出して、頭文字'_'のディレクトリのみを削除する。という要件があったのでメモ。
dirdel.c
# include <stdio.h>
# include <string.h>
# include <dirent.h>
# include <unistd.h>
# include <sys/stat.h>
int dirdel(char *path){
DIR *dir;
struct dirent *dp;
struct stat statBuf;
char childpath[512];
int nret = 0;
if (stat(path, &statBuf) == 0){
if((dir=opendir(path))==NULL){
perror("opendir");
return -1;
}
for(dp=readdir(dir);dp!=NULL;dp=readdir(dir)){
if(dp->d_name[0] != '.'){
sprintf(childpath, "%s/%s", path, dp->d_name);
nret = dirdel(childpath);
}
if(dp->d_name[0] == '_'){
if(rmdir(childpath) == 0){
}else{
nret = -1;
}
}
}
}
closedir(dir);
return nret;
}
int main(argc,argv)
int argc;
char *argv[];
{
char path[512];
int nret = 0;
if(argc<=1){
strcpy(path,".");
}
else{
strcpy(path,argv[1]);
}
nret = dirdel(path);
return nret;
}