我正在尝试从我的命令行解释器中删除所有文件和子目录。当调用 rmdir -s newFolder 时,我调用了一个函数 removeAll,它遍历所有文件和子文件夹并删除所有文件。
例如,如果我想删除文件 newFolder,我会删除所有文件并进入 newFolder1。我删除 newFolder1 中的所有文件并进入 newFolder2 并删除所有文件。所以现在我在 newFolder 2 中,newFolder、newFolder1 和 newFolder2 是空的。
我的问题是如何递归备份并删除这 3 个空文件夹。我已经调试并为此工作了几个小时,但我就是不明白。谢谢
此函数将成功删除一个空文件夹,否则调用 removeAll。
void MyShell::rmdir () {
//Error Check
if(argc != 3) {
printf("USAGE: rmdir [-s] <directory>\n");
return;
}
else if(stricmp(cwd, argv[2]) == 0){
printf("Cannot remove the current working directory");
return;
}
if(_rmdir(argv[2]) == 0)
return;
removeAll(argv[2]);
函数removeAll成功删除所有子文件夹中的所有文件
void removeAll(char *path)
{
_chdir(path);
_finddata_t data;
intptr_t handle = _findfirst("*", &data);
if(handle == -1)
{
return;
}
do
{
if (strcmp(data.name, ".") == 0 || strcmp(data.name, "..") == 0)
{
continue;
}
remove(data.name);
if(data.attrib & _A_SUBDIR)
{
removeAll(data.name);
}
} while(_findnext(handle, &data) != -1);
_findclose(handle);
}
我递归备份并删除所有子文件夹的想法是在它从 findnext 循环中断后调用一个方法
void removeDirectory(char *path)
{
_finddata_t data;
intptr_t handle = _findfirst("*", &data);
if(handle == -1)
{
return;
}
do
{
if (strcmp(data.name, ".") == 0 || strcmp(data.name, "..") == 0)
{
continue;
}
if(data.attrib & _A_SUBDIR)
{
if(_rmdir(data.name) == 0)
{
_chdir("..");
removeDirectory(path);
}
}
} while(_findnext(handle, &data) != -1);
_findclose(handle);
}
最佳答案
递归的全部要点是您不必“备份”。递归例程的每次迭代都应该只处理它自己的级别,然后再次调用自己或中断。看起来你几乎已经完成了。为您的 RemoveAll 例程尝试这样的事情:
void removeAll(char *path)
{
_chdir(path);
_finddata_t data;
intptr_t handle = _findfirst("*", &data);
if(handle == -1)
{
return;
}
while(_findnext(handle, &data) != -1) // changed from do..while to just while
{
if (strcmp(data.name, ".") == 0 || strcmp(data.name, "..") == 0)
{
continue;
}
if(data.attrib & _A_SUBDIR)
{
removeAll(data.name);
_rmdir(data.name); // <- moved this to here
}
else
{
remove(data.name);
}
}
_findclose(handle);
}
关于c++ - 递归删除目录和文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17053564/