您希望编写一个函数(递归函数最简单,但在深层目录上很容易耗尽堆栈空间),该函数将枚举目录的子目录.如果你发现一个子目录,你就会在这个目录上递归.否则,将删除其中的文件.完成后,目录为空,可以通过系统调用将其删除.
要枚举Unix上的目录,可以使用opendir()
、readdir()
和closedir()
.要删除,请在空目录中使用rmdir()
(即在函数结束时,删除子目录后),在文件中使用unlink()
.注意,在许多系统上,struct dirent
中的d_type
成员不受支持;在这些平台上,必须使用stat()
和S_ISDIR(stat.st_mode)
来确定给定路径是否为目录.
在Windows上,您将使用FindFirstFile()
/FindNextFile()
枚举,在空目录上使用RemoveDirectory()
,在删除文件时使用DeleteFile()
.
下面是一个可能在Unix上工作的示例(完全未经测试):
int remove_directory(const char *path) {
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
if (d) {
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) {
int r2 = -1;
char *buf;
size_t len;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);
else
r2 = unlink(buf);
}
free(buf);
}
r = r2;
}
closedir(d);
}
if (!r)
r = rmdir(path);
return r;
}