c++ - 递归删除目录和文件的问题

标签 c++ recursion directory

我正在尝试从我的命令行解释器中删除所有文件和子目录。当调用 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/

相关文章:

java - java数组中文件的访问路径

linux - 使用 perl 检查 Linux 中的目录是否存在

c++ - 检查c++中是否存在函数时出现问题

java - 以最少的运行时间存储带递归的斐波那契数列的值

c++ - 无法退出递归

python - 反向链表

c++ - ffmpeg 问题

c++ - Berkeley 套接字 API 与 C++ 网络编程库

c++ - 如何访问单元测试静态库的私有(private)成员

java - 在 Java 应用程序中的特定文件夹下创建 SQLite 数据库