gpt4 book ai didi

c - Linux 中 C 中的递归文件删除

转载 作者:太空狗 更新时间:2023-10-29 16:40:45 27 4
gpt4 key购买 nike

我有一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com