zoukankan      html  css  js  c++  java
  • linux --> 删除指定目录下所有文件

    删除指定目录下所有文件

    代码样例:

    /////////////////////////////////////////////////////
    //Name:           DeleteFile
    //Purpose:        Delete file in the special directory
    //Author:         xxxxxxxx
    //Created:        2011-12-01
    //Copy right: 
    //Licence: 
    //////////////////////////////////////////////////////
    
    #ifndef _DELETE_FILE
    #define _DELETE_FILE
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <dirent.h>
    #include <limits.h>
    #include <string.h>
    #include <stdio.h>
    #include <limits.h>
    
    //判断是否为目录
    bool is_dir(const char *path)
    {
        struct stat statbuf;
        if(lstat(path, &statbuf) ==0)//lstat返回文件的信息,文件信息存放在stat结构中
        {
            return S_ISDIR(statbuf.st_mode) != 0;//S_ISDIR宏,判断文件类型是否为目录
        }
        return false;
    }
    
    //判断是否为常规文件
    bool is_file(const char *path)
    {
        struct stat statbuf;
        if(lstat(path, &statbuf) ==0)
            return S_ISREG(statbuf.st_mode) != 0;//判断文件是否为常规文件
        return false;
    }
    
    //判断是否是特殊目录
    bool is_special_dir(const char *path)
    {
        return strcmp(path, ".") == 0 || strcmp(path, "..") == 0;
    }
    
    //生成完整的文件路径
    void get_file_path(const char *path, const char *file_name,  char *file_path)
    {
        strcpy(file_path, path);
        if(file_path[strlen(path) - 1] != '/')
            strcat(file_path, "/");
        strcat(file_path, file_name);
    }
    
    void delete_file(const char *path)
    {
        DIR *dir;
        dirent *dir_info;
        char file_path[PATH_MAX];
        if(is_file(path))
        {
            remove(path);
            return;
        }
        if(is_dir(path))
        {
            if((dir = opendir(path)) == NULL)
                return;
            while((dir_info = readdir(dir)) != NULL)
            {
                get_file_path(path, dir_info->d_name, file_path);
                if(is_special_dir(dir_info->d_name))
                    continue;
                delete_file(file_path);
                rmdir(file_path);
            }
        }
    }
    int main(int argc, char **argv)
    {
        delete_file("/Users/jiangtengfei/WorkSpace/test_code/tmp/asd");
        return 0;
    }
    #endif
  • 相关阅读:
    MyGeneration:开源的代码生成工具
    有了NHibernate就不再需要DAO了
    在vs编辑器里走来走去的快捷键
    asp.net的程序的一种简化结构
    取得gridview的行值
    asp.net中MVC模式的简单实现
    美味书签上的信息质量要好于博客RSS
    DAO已死,至少是中小型项目是这样
    免费好看的msdn中文杂志电子版
    Rhino Mocks是很不错的开源测试框架
  • 原文地址:https://www.cnblogs.com/jeakeven/p/9130444.html
Copyright © 2011-2022 走看看