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

  • [1. 关键词](#1. 关键词)
  • [2. fileutil.h](#2. fileutil.h)
  • [3. fileutil.cpp](#3. fileutil.cpp)
  • [4. filetype.h](#4. filetype.h)
  • [5. filesystem_win.cpp](#5. filesystem_win.cpp)
  • [6. filesystem_unix.cpp](#6. filesystem_unix.cpp)
  • [7. 源码地址](#7. 源码地址)

1. 关键词

C++ 文件系统操作 创建文件 删除文件 创建软连接 刪除软连接 跨平台

2. fileutil.h

c++ 复制代码
#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

c++ 复制代码
#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

c++ 复制代码
#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

c++ 复制代码
#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

c++ 复制代码
#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。

本文由博客一文多发平台 OpenWrite 发布!

相关推荐
anew___8 小时前
蜂鸣器播放音乐——让 Arduino 唱出旋律
c++·stm32·单片机·嵌入式硬件·c
stolentime9 小时前
洛谷P10515 转圈题解
c++·算法·数学建模·贪心算法
tdtsmt10 小时前
穿戴硬件量产工艺实录:天地通电子智能手表主板 SMT 贴片案
c++
m0_7345717614 小时前
深入理解C++ 析构函数<一>基本概念
开发语言·c++
t-think15 小时前
C++ string 类(上)—— string类初识与常用接口详解
开发语言·c++
cpp_learners15 小时前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
开发语言·c++·责任链模式
郝学胜_神的一滴15 小时前
C++11 工程级应用 12:编译期类型魔法,干掉重复与臃肿的代码
c++·visual studio
David猪大卫16 小时前
【C++修炼】哈希表的实现
数据结构·c++·笔记·学习·算法·哈希算法·散列表
广州山泉婚姻16 小时前
列表初始化:C++11全新初始化体系
c++·人工智能
莫生灬灬17 小时前
灵码 LingBuilder:用中文写代码,确定性生成真实 C++ 工程(开源)
c++·开源·mfc