首页 > 编程语言 >C++文件系统操作2 - 跨平台实现文件夹的创建和删除

C++文件系统操作2 - 跨平台实现文件夹的创建和删除

时间:2024-07-03 22:41:39浏览次数:1  
标签:return C++ 跨平台 文件夹 file path false include dir

1. 关键词

C++ 文件系统操作 创建文件夹 创建多级目录文件夹 删除文件夹 删除文件夹下的所有文件和子目录 跨平台

2. fileutil.h


#pragma once

#include <string>
#include <cstdio>
#include <cstdint>
#include "filetype.h"
#include "filepath.h"

namespace cutl
{

    /**
     * @brief The file guard class to manage the FILE pointer automatically.
     * file_guard object can close the FILE pointer automatically when his scope is exit.
     */
    class file_guard
    {
    public:
        /**
         * @brief Construct a new file guard object
         *
         * @param file the pointer of the FILE object
         */
        explicit file_guard(FILE *file);

        /**
         * @brief Destroy the file guard object
         *
         */
        ~file_guard();

        /**
         * @brief Get the FILE pointer.
         *
         * @return FILE*
         */
        FILE *getfd() const;

    private:
        FILE *file_;
    };

    /**
     * @brief Create a new directory.
     *
     * @param path the filepath of the new directory to be created
     * @param recursive whether to create parent directories, default is false.
     * If true, means create parent directories if not exist, like the 'mkdir -p' command.
     * @return true if the directory is created successfully, false otherwise.
     */
    bool createdir(const filepath &path, bool recursive = false);

    /**
     * @brief Remove a directory.
     *
     * @param path the filepath of the directory to be removed
     * @param recursive whether to remove the whole directory recursively, default is false.
     * If true, means remove the whole directory recursively, like the 'rm -rf' command.
     * @return true if the directory is removed successfully, false otherwise.
     */
    bool removedir(const filepath &path, bool recursive = false);

} // namespace cutl

3. fileutil.cpp

#include <cstdio>
#include <map>
#include <iostream>
#include <cstring>
#include <sys/stat.h>
#include "fileutil.h"
#include "inner/logger.h"
#include "inner/filesystem.h"
#include "strutil.h"

namespace cutl
{
    file_guard::file_guard(FILE *file)
        : file_(file)
    {
    }

    file_guard::~file_guard()
    {
        if (file_)
        {
            // CUTL_DEBUG("close file");
            int ret = fclose(file_);
            if (ret != 0)
            {
                CUTL_ERROR("fail to close file, ret" + std::to_string(ret));
            }
            file_ = nullptr;
        }
        // ROBOLOG_DCHECK(file_ == nullptr);
    }

    FILE *file_guard::getfd() const
    {
        return file_;
    }

    bool createdir(const filepath &path, bool recursive)
    {
        if (recursive)
        {
            constexpr int buf_size = MAX_PATH_LEN;
            char buffer[buf_size] = {0};
            int ret = snprintf(buffer, buf_size, "%s", path.str().c_str());
            if (ret < 0 || ret >= buf_size)
            {
                CUTL_ERROR("invalid path: " + path.str());
                return false;
            }
            int len = strlen(buffer);
            if (buffer[len - 1] != filepath::separator())
            {
                buffer[len++] = filepath::separator();
            }

            int32_t idx = (buffer[0] == filepath::separator()) ? 1 : 0;
            for (; idx < len; ++idx)
            {
                if (buffer[idx] != filepath::separator())
                {
                    continue;
                }
                buffer[idx] = '\0';
                filepath temp_path(buffer);
                if (!temp_path.exists())
                {
                    if (!create_dir(temp_path.str()))
                    {
                        CUTL_ERROR("createdir error. dir:" + temp_path.str());
                        return false;
                    }
                }
                buffer[idx] = filepath::separator();
            }
            return true;
        }
        else
        {
            auto dirPath = path.dirname();
            if (dirPath.empty())
            {
                CUTL_ERROR("invalid path: " + path.str());
                return false;
            }
            if (!cutl::path(dirPath).exists())
            {
                CUTL_ERROR("directory does not exist: " + dirPath);
                return false;
            }

            return create_dir(path.str());
        }
    }

    bool removedir(const filepath &path, bool recursive)
    {
        if (!path.exists())
        {
            CUTL_ERROR("directory does not exist: " + path.str());
            return false;
        }

        if (recursive)
        {
            return remove_dir_recursive(path.str());
        }
        else
        {
            return remove_dir(path.str());
        }
    }

4. filesystem_win.h


#include <vector>
#include <string>

#pragma once

namespace cutl
{
    bool create_dir(const std::string &dir_path);
    // remove empty directory
    bool remove_dir(const std::string &dir_path);
    // remove directory recursively
    bool remove_dir_recursive(const std::string &dir_path);
} // namespace cutl

5. filesystem_win.cpp

#if defined(_WIN32) || defined(__WIN32__)

#include <io.h>
#include <direct.h>
#include <Windows.h>
#include <stdlib.h>
#include "strutil.h"
#include "filesystem.h"
#include "logger.h"

namespace cutl
{
    bool create_dir(const std::string &dir_path)
    {
        if (_mkdir(dir_path.c_str()) != 0)
        {
            CUTL_ERROR("mkdir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }
        return true;
    }

    // remove empty directory
    // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/rmdir-wrmdir?view=msvc-170
    bool remove_dir(const std::string &dir_path)
    {
        if (_rmdir(dir_path.c_str()) != 0)
        {
            CUTL_ERROR("rmdir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }
        return true;
    }

    // remove directory recursively
    bool remove_dir_recursive(const std::string &dir_path)
    {
        auto findpath = dir_path + win_separator + "*.*";
        WIN32_FIND_DATAA data = {0};
        HANDLE hFind = FindFirstFileA(findpath.c_str(), &data);
        bool unicode = true;
        if (hFind == INVALID_HANDLE_VALUE || hFind == NULL)
        {
            CUTL_ERROR("FindFirstFileA failed for " + findpath + ", errCode: " + std::to_string(GetLastError()));
            return false;
        }

        do
        {
            auto dwAttrs = data.dwFileAttributes;
            auto filename = std::string(data.cFileName);
            if (is_special_dir(filename))
            {
                // “..”和“.”不做处理
                continue;
            }
            std::string filepath = dir_path + win_separator + filename;
            if ((dwAttrs & FILE_ATTRIBUTE_DIRECTORY))
            {
                // directory
                if (!remove_dir_recursive(filepath))
                {
                    FindClose(hFind);
                    return false;
                }
            }
            else
            {
                // file
                int ret = remove(filepath.c_str());
                if (ret != 0)
                {
                    CUTL_ERROR("remove " + filepath + " error, ret:" + std::to_string(ret));
                    return false;
                }
            }
        } while (FindNextFileA(hFind, &data));
        // 关闭句柄
        FindClose(hFind);

        // 删除当前文件夹
        if (_rmdir(dir_path.c_str()) != 0)
        {
            CUTL_ERROR("rmdir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }

        return true;
    }
} // namespace cutl

#endif // defined(_WIN32) || defined(__WIN32__)

6. filesystem_unix.cpp

#if defined(_WIN32) || defined(__WIN32__)
// do nothing
#else

#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stack>
#include <cstring>
#include <utime.h>
#include <stdlib.h>
#include <sys/time.h>
#include "filesystem.h"
#include "inner/logger.h"

namespace cutl
{
    bool create_dir(const std::string &dir_path)
    {
        if (mkdir(dir_path.c_str(), S_IRWXU | S_IRWXG | S_IRWXO | S_IWOTH) != 0)
        {
            CUTL_ERROR("mkdir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }
        return true;
    }

    bool remove_dir(const std::string &dir_path)
    {
        if (rmdir(dir_path.c_str()) != 0)
        {
            CUTL_ERROR("rmdir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }
        return true;
    }

    bool remove_dir_recursive(const std::string &dir_path)
    {
        DIR *dir = opendir(dir_path.c_str()); // 打开这个目录
        if (dir == NULL)
        {
            CUTL_ERROR("opendir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }
        struct dirent *file_info = NULL;
        // 逐个读取目录中的文件到file_info
        while ((file_info = readdir(dir)) != NULL)
        {
            // 系统有个系统文件,名为“..”和“.”,对它不做处理
            std::string filename(file_info->d_name);
            if (is_special_dir(filename))
            {
                continue;
            }
            struct stat file_stat; // 文件的信息
            std::string filepath = dir_path + unix_separator + filename;
            int ret = lstat(filepath.c_str(), &file_stat);
            if (0 != ret)
            {
                CUTL_ERROR("stat error. filepath:" + filepath + ", error:" + strerror(errno));
                closedir(dir);
                return false;
            }
            if (S_ISDIR(file_stat.st_mode))
            {
                if (!remove_dir_recursive(filepath))
                {
                    closedir(dir);
                    return false;
                }
            }
            else
            {
                int ret = remove(filepath.c_str());
                if (ret != 0)
                {
                    CUTL_ERROR("remove " + filepath + " error, ret:" + std::to_string(ret));
                    closedir(dir);
                    return false;
                }
            }
        }
        closedir(dir);

        // 删除当前文件夹
        int ret = rmdir(dir_path.c_str());
        if (ret != 0)
        {
            CUTL_ERROR("rmdir error. dir_path:" + dir_path + ", error:" + strerror(errno));
            return false;
        }

        return true;
    }
} // namespace cutl

#endif // defined(_WIN32) || defined(__WIN32__)

7. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

标签:return,C++,跨平台,文件夹,file,path,false,include,dir
From: https://www.cnblogs.com/luoweifu/p/18282684

相关文章

  • C++从淬体到元婴day10之模板
    2024/6/30模板概念:在C++中,模板是一种泛型编程的工具,它允许程序员编写与类型无关的代码。作用:通过使用模板,你可以编写一种可以处理多种数据类型的函数或类,而无需为每种数据类型编写单独的实现。分类:函数模板和类模板函数模板建立一个通用函数,其函数返回值类型和形参类......
  • 1.选择排序(C++)
    //算法步骤//1.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。//2.再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。//3.重复第二步,直到所有元素均排序完毕。//以下是代码实现//选择排序#include<iostream>#include<iomanip>using......
  • C++ 彻底搞懂指针(3)
    1.数组指针、二维数组指针、字符串指针1.1定义一个数组指针前面说过,指针变量存放的是地址,它可以存放普通变量的地址,可以存放另一个指针变量的地址,当然也可以存放数组、结构体、函数的地址。如果一个指针指向了数组,就称它为数组指针,比如下面的代码就定义了一个指针p指向......
  • C++修改任务计划程序-电源条件
    介绍应用程序需要进行守护,又不想另外运行一个软件去实时监测应用程序是否退出了,退出就重启。在Windows上可以利用任务计划程序,达到守护进程的作用。创建任务计划在nsis脚本中可以直接使用schtasks命令来创建任务计划,以下是每分钟检测一次的脚本。nsExec::ExecToLog'schtask......
  • 新特性之C++14
    C++14是C++11的一个增量升级版本,虽然没有引入像C++11那样的大量新特性,但它通过对已有特性进行优化和扩展,提高了语言的可用性和性能。本文将详细介绍C++14引入和优化的新特性功能。概述C++14旨在修复C++11的一些缺陷,并提供了一些重要的增强功能,以简化开发者的日......
  • 构建支持多平台的返利App跨平台开发策略
    构建支持多平台的返利App跨平台开发策略大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将讨论如何构建支持多平台的返利App,特别关注跨平台开发策略,以提高应用的覆盖范围和用户体验。为什么选择跨平台......
  • PointCloudLib alpha shapes算法提取平面点云边界 C++版本
    测试效果算法简介AlphaShapes算法是一种用于提取平面点云边界特征的方法,以下是对其原理和步骤的详细解释:1.AlphaShapes算法概述目标:从点云数据中提取曲面边界信息,通过计算点云中点的Alpha形状,获得边界特征。Alpha形状:一个可以描述几何体边界的参数。其计算基于一......
  • 基于C++类与权限初识:银行系统
    功能:银行的账户是一个模板,是一个类,有存款人信息和账户额度,而具体的存款人视为一个对象,一个对象不能私自修改账户额度,需要通过一个操作流程,比如去ATM或者柜台进行操作才能修改到账户额度,所以,存款人信息和账户额度设计成私有权限,通过公有的操作流程,也就是公有函数去操作私有......
  • python 输入文件夹路径,返回所有的层次结构 excel
    importosimportopenpyxlfromopenpyxl.stylesimportFontdefget_folder_structure(root_folder):folder_structure=[]forroot,dirs,filesinos.walk(root_folder):level=root.replace(root_folder,'').count(os.sep)indent=......
  • 聊聊C++20的三向比较运算符 `<=>`
    C++20标准引入了许多新特性,其中之一是三向比较运算符<=>,也被称为太空船运算符。这个新运算符为C++程序员提供了一种全新的比较对象的方式,它能有效简化比较逻辑,避免编写多个比较运算符重载的情况。为什么需要三向比较运算符?在C++20之前,如果要完整地定义一个类型的比较行为......