递归删除目录

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <utime.h>
#include <iostream>
using namespace std;

#define TIME_CHN_FMT "%Y-%m-%d %H:%M:%S"

char* timeToString(time_t tmTime, const char *fmt,char *strTime, int len)
{
    struct tm gmTime;
    localtime_r(&tmTime, &gmTime);
    strftime(strTime, (size_t) len, fmt, &gmTime);

    return strTime;
}

int removeDir(const char* dirStr)
{
    struct dirent* subPath = NULL;
    DIR* dir = opendir(dirStr);
    if(dir==NULL)
    {
        cout << "打开目录失败,dir:" << dirStr << endl;
        return -1;
    }
    cout << "删除目录开始,path:" << dirStr << endl;
    while((subPath=readdir(dir))!=NULL)
    {
        if(strcmp(subPath->d_name,".")==0||strcmp(subPath->d_name,"..")==0){
            continue;
        }
        struct stat statBuf;
        char subPathStr[256];
        bzero(subPathStr,sizeof(subPathStr));
        strcpy(subPathStr,dirStr);
        strcat(subPathStr,"/");
        strcat(subPathStr,subPath->d_name);
        lstat(subPathStr,&statBuf);
        if(S_ISDIR(statBuf.st_mode))
        {
            removeDir(subPathStr);
            continue;
        }
        char createTime[32],accessTime[32],modifyTime[32];
        bzero(createTime,sizeof(createTime));
        bzero(accessTime,sizeof(accessTime));
        bzero(modifyTime,sizeof(modifyTime));
        timeToString(statBuf.st_ctime,TIME_CHN_FMT,createTime,sizeof(createTime));
        timeToString(statBuf.st_atime,TIME_CHN_FMT,accessTime,sizeof(accessTime));
        timeToString(statBuf.st_mtime,TIME_CHN_FMT,modifyTime,sizeof(modifyTime));
        cout << "删除文件:" << subPathStr << ",创建时间:" << createTime << ",最后访问时间:"
             << accessTime<< ",最后修改时间:" << modifyTime << endl;

        unlink(subPathStr);
    }
    cout << "删除目录结束,path:" << dirStr << endl;
    rmdir(dirStr);
    return 0;
}

int main()
{
    char dirStr[128] = "/home/code/apue_debug/test";
    removeDir(dirStr);
}

删除目录开始,path:/home/code/apue_debug/test
删除文件:/home/code/apue_debug/test/dirFile,创建时间:2014-08-12 16:02:55,最后访问时间:2014-08-12 16:02:55,最后修改时间:2014-08-12 16:02:55
删除目录开始,path:/home/code/apue_debug/test/subDir
删除文件:/home/code/apue_debug/test/subDir/subDirFile,创建时间:2014-08-12 16:02:59,最后访问时间:2014-08-12 16:02:59,最后修改时间:2014-08-12 16:02:59
删除目录结束,path:/home/code/apue_debug/test/subDir
删除目录结束,path:/home/code/apue_debug/test

你可能感兴趣的:(递归)