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

Linux下递归遍历指定目录下的文件内容并删除的函数实现

2016-06-11 22:38 946 查看
#include <stdio.h>

#include <string.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <dirent.h>

int is_dir(const char *path)  // 判断是否为目录

{

   struct stat statbuf;

   if(stat(path, &statbuf) == 0)  //将path文件名信息写入stat结构体

   {

       return S_ISDIR(statbuf.st_mode); //返回是否为目录

   }

   return 0;

}

int is_file(const char *path)  //判断是否为文件

{

    struct stat statbuf;

    if(stat(path, &statbuf) == 0) //将path文件名信息写入stat结构体

    {

        return S_ISREG(statbuf.st_mode); //返回是否为文件

    }

    return 0;
}

int is_special_file(const char *path)  //判断是否为“.”或".."

{

    return (strcmp(path, ".") == 0 || strcmp(path, "..") == 0);

}

void get_file_path(const char *path, const char *filename, char *file_path)  //组合路径和当前目录名,成为新路径:file_path

{

    strcpy(file_path, path);

    if(file_path[strlen(file_path) - 1] != '/')

    {

        strcat(file_path, "/");

    }

    strcat(file_path, filename);

    return;

}

void delete_file(const char *path)

{

    DIR *dir;

    struct dirent *dir_info;

    char file_path[100];

    if(is_file(path))  //判断是否为文件

    {

        printf("delete:%s\n", path);

        remove(path);

        return;
    }

    if(is_dir(path))  // 判断是否为目录

    {

        if((dir = opendir(path)) == NULL)  //目录打开失败返回

        {

            return;

        }

        while(dir_info = readdir(dir))

        {

            if(is_special_file(dir_info->d_name))  //判断是否为“.”或".."

            {

                continue;

            }

            get_file_path(path,dir_info->d_name, file_path);  //组合路径和当前目录名,成为新路径:file_path

            delete_file(file_path);

        }

        rmdir(path);  //删除空目录

        printf("rmdir: %s\n", path);

    }

}

 int main()

{

     delete_file("./aaa");

     return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: