【发布时间】:2016-04-18 05:43:32
【问题描述】:
对于我的 OS 类,我必须递归删除 C 中不一定为空的目录。我试图这样做,但它似乎不起作用。不过,当我编译它时,我的代码中没有错误。任何建议都会对我有很大帮助。
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
int main(int argc,char* argv[])
{
if (argc<2) {
printf("Wrong numer of arguments\n");
return 1;
}
int is_dir (char * filename)
{
struct stat buf;
int ret = stat (filename, & buf);
if (0 == ret)
{
if (buf.st_mode & S_IFDIR)
{
return 0;
}
else
{
return 1;
}
}
return -1;
}
int delete_dir (char * dirname)
{
char chBuf [256];
DIR * dir = NULL;
struct dirent * ptr;
int ret = 0;
dir = opendir (dirname);
if (NULL == dir)
{
return -1;
}
while ((ptr = readdir (dir))!= NULL)
{
ret = strcmp (ptr-> d_name, ".");
if (0 == ret)
{
continue;
}
ret = strcmp (ptr-> d_name, "..");
if (0 == ret)
{
continue;
}
snprintf (chBuf, 256, "%s /%s", dirname, ptr-> d_name);
ret = is_dir (chBuf);
if (0 == ret)
{
ret = delete_dir(chBuf);
if (0!=ret)
{
return -1;
}
}
else if (1 == ret)
{
ret = remove (chBuf);
if (0!=ret)
{
return -1;
}
}
}
closedir (dir);
ret = remove (dirname);
if (0!= ret)
{
return -1;
}
return 0;
}
}
谢谢!
【问题讨论】:
-
这是一个“请调试我的代码”的问题吗?例如,您可以告诉运行它时会发生什么,以及您期望发生什么。您也可以对代码稍加注释,这样读者就不必猜测了。此代码是否使用嵌套函数,或者这是什么?你可以尝试格式化你的代码。它不易阅读。
-
你在main里面写函数块!!!!!!
-
看看
nftw()函数,它对你的目的非常有用。 -
另外,
(buf.st_mode & S_IFDIR)是错误的。请改写S_ISDIR(buf.st_mode)。 -
首先你应该正确缩进你的程序。
标签: c linux recursion directory