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

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

时间:2024-07-01 21:31:14浏览次数:1  
标签:return filepath 文件系统 C++ 跨平台 file path include const

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 file.
     *
     * @param path the filepath of the new file to be created
     * @return true if the file is created successfully, false otherwise.
     */
    bool createfile(const filepath &path);

    
    /**
     * @brief Create a symbolic link or shortcut.
     *
     * @param referenece the real path referenced by the symbolic link or shortcut
     * @param filepath the filepath of the symbolic link or shortcut to be created
     * @return true if the symbolic link or shortcut is created successfully, false otherwise.
     */
    bool createlink(const filepath &referenece, const filepath &filepath);

    /**
     * @brief Remove a regular file or symbolic link(shortcut on windows).
     *
     * @param path the filepath of the file or symbolic link to be removed
     * @return true if the file or symbolic link is removed successfully, false otherwise.
     */
    bool removefile(const filepath &path);

} // 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 createfile(const filepath &path)
    {
        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;
        }

        file_guard fg(fopen(path.str().c_str(), "w"));
        if (fg.getfd() == nullptr)
        {
            CUTL_ERROR("fail to open file:" + path.str());
            return false;
        }

        int ret = fflush(fg.getfd());
        if (0 != ret)
        {
            CUTL_ERROR("fail to flush file:" + path.str());
            return false;
        }

        if (!file_sync(fg.getfd()))
        {
            CUTL_ERROR("file_sync failed for " + path.str());
            return false;
        }

        return true;
    }

    bool createlink(const filepath &referenece, const filepath &filepath)
    {
        return file_createlink(referenece.str(), filepath.str());
    }

    bool removefile(const filepath &path)
    {
        int ret = remove(path.str().c_str());
        if (ret != 0)
        {
            CUTL_ERROR("remove " + path.str() + " error, ret:" + std::to_string(ret));
            return false;
        }
        return true;
    }

4. filetype.h


#include <vector>
#include <string>

#pragma once

namespace cutl
{
    // 创建软连接或快捷方式
    bool file_createlink(const std::string &referenece, const std::string &filepath);
} // 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 file_createlink(const std::string &referenece, const std::string &filepath)
    {
        CUTL_ERROR("file_createlink() is not supported on Windows");
        return false;
    }
} // 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 file_createlink(const std::string &referenece, const std::string &filepath)
    {
        int ret = ::symlink(referenece.c_str(), filepath.c_str());
        if (ret != 0)
        {
            CUTL_ERROR("symlink error. filepath:" + filepath + ", referenece:" + referenece + ", error:" + strerror(errno));
            return false;
        }
        return true;
    }
} // namespace cutl

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

7. 源码地址

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

标签:return,filepath,文件系统,C++,跨平台,file,path,include,const
From: https://www.cnblogs.com/luoweifu/p/18278894

相关文章

  • 深入解析C++标准库中的std::vector容器
    1.底层实现std::vector 是C++标准库中的一个模版类,用于动态数组。它的底层实现可以理解为一个动态分配的连续内存块,当需要更多空间时,内存会自动扩展。内存分配:vector 使用一块连续的内存存储元素。当插入新元素导致容量不足时,vector 会分配一块更大的内存(通常是当前容量......
  • C++仿SKData实现C原生指针管理
    template<typenameT>classHBData{public:HBData(T*other_data,size_tother_size,boolrelease):data(other_data),size(other_size),isDeepCopy(release){}HBData(constHBData&other){if(isDeepCopy&&data)......
  • C/C++ Dijkstra(迪杰斯特拉)算法详解及源码
    Dijkstra(迪杰斯特拉)算法是一种用于寻找带权重图中的最短路径的算法。它由荷兰计算机科学家EdsgerDijkstra于1956年提出,被广泛应用于网络路由算法和地图路线规划等领域。算法思想:初始化一个距离数组,用于保存起点到每个顶点的当前最短距离(初始时将起点距离设置为0,其他顶......
  • 信息学奥赛一本通C++版 1081:分苹果 答案
    目录【链接】【题目描述】【输入】【输出】【输入样例】【输出样例】【答案】【链接】1081:分苹果1081:分苹果【题目描述】把一堆苹果分给n个小朋友,要使每个人都能拿到苹果,而且每个人拿到的苹果数都不同的话,这堆苹果至少应该有多少个?【输入】一个不大于1000的......
  • 奥赛一本通C++版 1057解题思路(附加答案)
    链接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1057题目:解题思路:先定义两个整型变量a和b,一个字符变量c,依次输入a,b,c。接着判断输入的运算符号是否等于+ || - || * || /(注意,这里的符号用单引号括起来)。如果运算符号等于加号,则进行加法运算,把a和b相加,......
  • 用C++解决编程题目:角谷猜想
    学习目标:用C++编写简单的题目学习内容:#include<iostream>usingnamespacestd;intmain(){longlongn;cin>>n;while(n!=1){if(n%2==1){cout<<n<<"*3+1="<<n*3+1<<endl;n=3*n+1;......
  • C++实现简化版Qt的QObject(3):增加父子关系、属性系统
    前几天写了文章:C++实现一个简单的Qt信号槽机制C++实现简化版Qt信号槽机制(2):增加内存安全保障之后感觉还不够过瘾,Qt中的QObject体系里还有不少功能特性没有实现。为了提高QObject的还原度,今天我们将父子关系、属性系统等功能也一并实现。接口设计首先,我们设计一下我们的......
  • 超详细的 C++中的封装继承和多态的知识总结<1.封装>
    引言  小伙伴们都知道C++面向对象难,可是大家都知道,这个才是C++和C的真正区别的地方,也是C++深受所有大厂喜爱的原因,它的原理更接近底层,它的逻辑更好,但是学习难度高,大家一定要坚持下来呀,本章呢对于C++有关的知识开始讲解封装继承和多态。好了啦废话不多说,跟着小杨一起开始......
  • 华为OD机试D卷 --智能成绩表--24年OD统一考试(Java & JS & Python & C & C++)
    文章目录题目描述输入描述输出描述用例题目解析算法源码题目描述小明来到某学校当老师,需要将学生按考试总分或单科分数进行排名,你能帮帮他吗?输入描述第1行输入两个整数,学生人数n和科目数量m。0<n<1000<m<10第2行输入m个科目名称,彼......
  • 华为OD机试D卷 --最富裕的小家庭--24年OD统一考试(Java & JS & Python & C & C++)
    文章目录题目描述输入描述输出描述用例题目解析算法源码题目描述在一颗树中,每个节点代表一个家庭成员,节点的数字表示其个人的财富值,一个节点及其直接相连的子节点被定义为一个小家庭。现给你一颗树,请计算出最富裕的小家庭的财富和。输入描述第一行为一......