rmdir()函数只能删除空目录,对于非空目录,可以使用如下代码段:
static int rm_dir(const char *path)
{
char dir_name[MAX_FILE_NAME_LEN] = {0};
DIR *dirp;
struct dirent *dp;
struct stat dir_stat;
if (0 != access(path, F_OK))
return 0;
if (0 > stat(path, &dir_stat))
{
err_set(ERR_GENERIC_ERROR, "stat() %s failed.", path);
goto err_1;
}
if (S_ISREG(dir_stat.st_mode))
remove(path);
else if (S_ISDIR(dir_stat.st_mode))
{
if((dirp = opendir(path)) == NULL)
{
err_set(ERR_GENERIC_ERROR, "opendir %s failed.", path);
goto err_1;
}
while ((dp = readdir(dirp)) != NULL)
{
if ((0 == strcmp(".", dp->d_name)) || (0 == strcmp("..", dp->d_name)))
continue;
sprintf(dir_name, "%s%c%s", path, DIRSYMBOL, dp->d_name);
rm_dir(dir_name); //递归调用
}
closedir(dirp);
rmdir(path);
}
return 0;
err_1:
if (dirp != NULL)
closedir(dirp);
return -1;
}