0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

パラメータに指定したパス以下から、頭文字'_'のディレクトリのみを削除

Last updated at Posted at 2019-04-14

再帰的に呼び出して、頭文字'_'のディレクトリのみを削除する。という要件があったのでメモ。

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;
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?