我有一个 C 程序,在程序的某个时刻有这个:
系统("rm -rf foo");
其中 foo 是一个目录。我决定,与其调用系统,不如直接在代码中执行递归删除。我假设一段代码很容易找到。傻我。无论如何,我最终写下了这个:
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
#include <libgen.h>
int recursiveDelete(char* dirname) {
DIR *dp;
struct dirent *ep;
char abs_filename[FILENAME_MAX];
dp = opendir (dirname);
if (dp != NULL)
{
while (ep = readdir (dp)) {
struct stat stFileInfo;
snprintf(abs_filename, FILENAME_MAX, "%s/%s", dirname, ep->d_name);
if (lstat(abs_filename, &stFileInfo) < 0)
perror ( abs_filename );
if(S_ISDIR(stFileInfo.st_mode)) {
if(strcmp(ep->d_name, ".") &&
strcmp(ep->d_name, "..")) {
printf("%s directory\n",abs_filename);
recursiveDelete(abs_filename);
}
} else {
printf("%s file\n",abs_filename);
remove(abs_filename);
}
}
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
remove(dirname);
return 0;
}
这似乎可行,但我不敢在生产中实际使用它。我确定我做错了什么。有谁知道 C 库可以执行我错过的递归删除,或者有人可以指出我犯的任何错误吗?
谢谢。
最佳答案
POSIX 有一个函数叫做 ftw(3) (文件树遍历)那个
walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree.
关于c - Linux 中 C 中的递归文件删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3833581/