您的位置:首页 > 运维架构 > Linux

linux系统调用之文件:递归删除非空目录

2013-08-15 09:59 513 查看
#include <sys/types.h>  
#include <dirent.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <sys/stat.h>  
#include <unistd.h>  
#define BUF_LEN 1024  
  
//int stat(const char *path, struct stat *buf);  
//int fstat(int filedes, struct stat *buf);  
//int lstat(const char *path, struct stat *buf);  
  
//int remove(const char *pathname);  
//struct dirent *readdir(DIR *dir);  
//DIR *opendir(const char *name);  
  
void rm(char * name)  
{  
    DIR *dir;  
    struct dirent *read_dir;  
    struct stat st;  
    char buf[BUF_LEN];  
  
    if(lstat(name, &st) < 0)  
    {  
        fprintf(stderr, "Lstat Error!/n");  
        exit(1);  
    }  
  
    if(S_ISDIR(st.st_mode))  
    {  
        if((dir = opendir(name)) == NULL)  
        {  
            fprintf(stderr, "remove [%s] faild/n", name);  
            exit(1);  
        }  
      
        while((read_dir = readdir(dir)) != NULL)  
        {  
            if(strcmp(read_dir->d_name, ".") == 0 ||  
                strcmp(read_dir->d_name, "..") == 0)  
                continue;  
            sprintf(buf, "%s/%s", name, read_dir->d_name);  
            rm(buf);  
        }  
    }  
    printf("rm :%s/n", name);  
    if(remove(name) < 0)  
    {  
        fprintf(stderr, "remove [%s] faild/n", name);  
    }  
}  
  
int main(int argc, char **argv)  
{  
    if(argc < 1)  
    {  
        fprintf(stderr, "Usage <%s><file>/n", argv[0]);  
    }  
    rm(argv[1]);  
  
    return 0;  
}  
分享到:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  递归 Linux