递归删除使用C目录 [英] Recursively remove a directory using C

查看:185
本文介绍了递归删除使用C目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这个工具我自己和我拿出这样的:

I want to implement this myself and I come up something like this:

/* DIR *opendir(const char *name);
 *
 * Open a directory stream to argv[1] and make sure
 * it's a readable and valid (directory) */
if ((dip = opendir(argv[1])) == NULL)
{
        perror("opendir");
        return 0;
}

printf("Directory stream is now open\n");

/*  struct dirent *readdir(DIR *dir);
 *
 * Read in the files from argv[1] and print */
while ((dit = readdir(dip)) != NULL)
{
        printf("\n%s", dit->d_name);
        remove(dit->d_name);
}

我猜我已经开始从最深层次的东西删除,然后上去,但现在看来READDIR不给我这个顺序。

I am guessing I have to start delete things from the deepest level and then go up, but now it seems readdir does not give me that order.

请帮忙,谢谢!

推荐答案

您必须先下来递归一路到较低的水平,如下面的伪code:

You have to recurse all the way down to the lower levels first, as in the following pseudo code:

def delDir (d):
    # Delete the directories by recursion, files straight away.

    for every item in d:
        if item is a directory:
            delDir (item)
        else:
            delete file item

    # Finally, remove the directory itself.

    remove directory d

这是真的,这保证了您尝试删除父之前降低所有目录和文件将被删除。

That's it really, this guarantees that all lower directories and files are deleted before you attempt to remove the parent.

由于项目很可能是刚刚目录的电流分量,则可能需要使用来构建一个完整的名称,例如,的strcpy / strcat的

Since item is likely to be just the current component of the directory, you may need to construct a full name using, for example, strcpy/strcat:

def delDir (dirName):
    def localBuff[enoughSpace]

    # Delete the directories by recursion, files straight away.

    dirHandle = dirOpen (dirName)
    itemName = dirnext (dirHandle)
    while itemName is valid:
        if itemName <> "." and itemName <> "..":
            strcpy dirName to localBuff
            strcat "/" to localBuff
            strcat itemName to localBuff

            if itemName is a directory:
                delDir (localBuff)
           else:
                delete file localBuff

        itemName = dirnext (dirHandle)

    dirClose (dirHandle)

    # Finally, remove the directory itself.

    remove directory dirName

这篇关于递归删除使用C目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆