如何在C或C++中删除非空目录?有什么功能吗? rmdir 只删除空目录。请提供一种不使用任何外部库的方法。
还告诉我如何用 C 或 C++ 删除文件?
您想要编写一个函数(递归函数是最简单的,但很容易耗尽深层目录上的堆栈空间)来枚举目录的子目录。如果您发现一个子目录是目录,则可以对其进行递归。否则,你就删除里面的文件。完成后,该目录为空,您可以通过系统调用将其删除。
要枚举 Unix 上的目录,您可以使用opendir()
, readdir()
, and closedir()
。要删除您使用rmdir()
在空目录上(即在函数末尾,删除子目录后)unlink()
在一个文件上。请注意,在许多系统上d_type
成员于struct dirent
不支持;在这些平台上,您将必须使用stat()
and 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)