C++文件路径处理2 - 路径拼接路径解析

  • 1. 关键词
  • 2. filesystem.h
  • 3. filepath.cpp
  • 6. 测试代码
  • 7. 运行结果
  • 8. 源码地址

1. 关键词

关键词:

C++ 文件路径处理 路径拼接 获取父目录的路径 获取文件名 获取拓展名 跨平台

应用场景:

  • 路径的拼接
  • 路径的解析

2. filesystem.h


#pragma once

#include <string>
#include <iostream>
#include <cstdio>
#include "filetype.h"

namespace cutl
{

    /**
     * @brief The class for file path operations.
     *
     */
    class filepath
    {
    public:
        /**
         * @brief Construct a new filepath object
         *
         * @param path file path string
         */
        filepath(const std::string &path);

        /**
         * @brief Construct a new filepath object by copy
         *
         * @param other other filepath object
         */
        filepath(const filepath &other);

        /**
         * @brief Assign operator, assign a new filepath object by copy
         *
         * @param other other filepath object
         * @return filepath& the reference of the current filepath object
         */
        filepath &operator=(const filepath &other);

        /**
         * @brief Destroy the filepath object
         *
         */
        ~filepath() = default;

    public:
        /**
         * @brief Get the path separator of the current os platform.
         *
         * @return the path separator
         */
        static char separator();

        /**
         * @brief Get the string of the filepath.
         *
         * @return the filepath
         */
        std::string str() const;

        /**
         * @brief Join the current filepath with a new filename.
         *
         * @param filename the filename to be joined
         * @return the new filepath object
         */
        filepath join(const std::string &filename) const;

        /**
         * @brief Get the parent directory of the filepath.
         *
         * @return parent directory path
         */
        std::string dirname() const;

        /**
         * @brief Get the filename or directory name of the filepath.
         *
         * @return filename or directory name
         */
        std::string basename() const;
        /**
         * @brief Get the extension of the filepath.
         *
         * @return extension with dot
         */
        std::string extension() const;

    private:
        std::string filepath_;
    };

    /**
     * @brief Define the output stream operator for filepath object.
     *
     * @param os the std::ostream object
     * @param fp the filepath object to be output
     * @return std::ostream& the reference of the std::ostream object after outputing the filepath object.
     */
    std::ostream &operator<<(std::ostream &os, const filepath &fp);

    /**
     * @brief Create a filepath object from a string.
     *
     * @param path file path string
     * @return filepath object
     */
    filepath path(const std::string &path);

} // namespace cutl

3. filepath.cpp


#include "filepath.h"
#include "inner/logger.h"
#include "inner/filesystem.h"
#include "strutil.h"
#include "sysutil.h"

namespace cutl
{
    static constexpr char win_separator = '\\';
    static constexpr char unix_separator = '/';

    void fixpath(std::string &path)
    {
        if (win_separator == filepath::separator())
        {
            for (size_t i = 0; i < path.size(); i++)
            {
                if (path[i] == unix_separator)
                {
                    path[i] = win_separator;
                }
            }
        }
        else if (unix_separator == filepath::separator())
        {
            for (size_t i = 0; i < path.size(); i++)
            {
                if (path[i] == win_separator)
                {
                    path[i] = unix_separator;
                }
            }
        }
        else
        {
            // do nothing
        }

        while (path.empty() || path.back() == filepath::separator())
        {
            path.pop_back();
        }
    }

    filepath::filepath(const std::string &path)
    {
        filepath_ = path;
        fixpath(filepath_);
    }

    filepath::filepath(const filepath &other)
    {
        filepath_ = other.filepath_;
    }

    filepath &filepath::operator=(const filepath &other)
    {
        this->filepath_ = other.filepath_;
        return *this;
    }

    char filepath::separator()
    {
#if defined(_WIN32) || defined(__WIN32__)
        return win_separator;
#else
        return unix_separator;
#endif
    }

    std::string filepath::str() const
    {
        return filepath_;
    }

    filepath filepath::join(const std::string &filename) const
    {
        std::string path = filepath_ + separator() + filename;
        return filepath(path);
    }

    std::string filepath::dirname() const
    {
        auto index = filepath_.find_last_of(separator());
        if (index == std::string::npos)
        {
            return "";
        }
        return filepath_.substr(0, index);
    }

    std::string filepath::basename() const
    {
        auto index = filepath_.find_last_of(separator());
        // auto len = filepath_.length() - index - 1;
        if (index == std::string::npos)
        {
            return filepath_;
        }
        return filepath_.substr(index + 1);
    }

    std::string filepath::extension() const
    {
        auto pos = filepath_.find_last_of('.');
        if (pos == std::string::npos)
        {
            return "";
        }

        return filepath_.substr(pos);
    }

    std::ostream &operator<<(std::ostream &os, const filepath &fp)
    {
        os << fp.str();
        return os;
    }

    filepath path(const std::string &path)
    {
        return filepath(path);
    }
} // namespace cutl

6. 测试代码

#include "common.hpp"
#include "fileutil.h"

void TestJoin()
{
    PrintSubTitle("TestJoin");

    auto path1 = cutl::path("/Users/spencer/workspace/common_util/src/usage_demo");
    auto path2 = path1.join("filepath.hpp");

    std::cout << "path1: " << path1 << std::endl;
    std::cout << "path2: " << path2 << std::endl;
}

void TestDirnameBasename()
{
    PrintSubTitle("TestDirnameBasename");

    auto path1 = cutl::path("/Users/spencer/workspace/common_util/src/usage_demo/filepath.hpp");
    std::cout << "path1: " << path1 << std::endl;
    std::cout << "dirname: " << path1.dirname() << std::endl;
    std::cout << "basename: " << path1.basename() << std::endl;
    auto path2 = cutl::path("/Users/spencer/workspace/common_util/src/usage_demo");
    std::cout << "path2: " << path2 << std::endl;
    std::cout << "dirname: " << path2.dirname() << std::endl;
    std::cout << "basename: " << path2.basename() << std::endl;
    auto path3 = cutl::path("filepath.hpp");
    std::cout << "path3: " << path3 << std::endl;
    std::cout << "dirname: " << path3.dirname() << std::endl;
    std::cout << "basename: " << path3.basename() << std::endl;
}

void TestExtenstion()
{
    PrintSubTitle("TestExtenstion");

    auto path1 = cutl::path("/Users/spencer/workspace/common_util/src/usage_demo/filepath.hpp");
    std::cout << "path1: " << path1 << ", extension: " << path1.extension() << std::endl;
    auto path2 = cutl::path("/Users/spencer/workspace/common_util/src/usage_demo/filepath");
    std::cout << "path2: " << path2 << ", extension: " << path2.extension() << std::endl;
}

7. 运行结果

----------------------------------------------TestJoin----------------------------------------------
path1: /Users/spencer/workspace/common_util/src/usage_demo
path2: /Users/spencer/workspace/common_util/src/usage_demo/filepath.hpp
----------------------------------------TestDirnameBasename-----------------------------------------
path1: /Users/spencer/workspace/common_util/src/usage_demo/filepath.hpp
dirname: /Users/spencer/workspace/common_util/src/usage_demo
basename: filepath.hpp
path2: /Users/spencer/workspace/common_util/src/usage_demo
dirname: /Users/spencer/workspace/common_util/src
basename: usage_demo
path3: filepath.hpp
dirname: 
basename: filepath.hpp
-------------------------------------------TestExtenstion-------------------------------------------
path1: /Users/spencer/workspace/common_util/src/usage_demo/filepath.hpp, extension: .hpp
path2: /Users/spencer/workspace/common_util/src/usage_demo/filepath, extension: 

8. 源码地址

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/753058.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ZW3D二次开发_CAM_添加刀具

在ZW3D2025中可以通过库添加刀具&#xff0c;代码如下&#xff1a; int idx_tool;int ret ZwCamToolInsertFromLibrary("", "001 METRIC TOOLS.xlsx", "10 mm Flat Endmill", &idx_tool); 平台功能添加刀具如下&#xff1a;

【Linux】进程间通信_2

文章目录 七、进程间通信1. 进程间通信分类管道 未完待续 七、进程间通信 1. 进程间通信分类 管道 管道的四种情况&#xff1a; ①管道内部没有数据&#xff0c;并且具有写端的进程没有关闭写端&#xff0c;读端就要阻塞等待&#xff0c;知道管道pipe内部有数据。 ②管道内部…

esp8266 GPIO

功能综述 ESP8266 的 16 个通⽤ IO 的管脚位置和名称如下表所示。 管脚功能选择 功能选择寄存器 PERIPHS_IO_MUX_MTDI_U&#xff08;不同的 GPIO&#xff0c;该寄存器不同&#xff09; PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U,FUNC_GPIO12);PERIPHS_IO_MUX_为前缀。后面的…

uniapp开发企业微信内部应用

最近一直忙着开发项目&#xff0c;终于1.0版本开发完成&#xff0c;抽时间自己总结下在项目开发中遇到的技术点。此次项目属于自研产品&#xff0c;公司扩展业务&#xff0c;需要在企业微信中开发内部应用。因为工作中使用的是钉钉&#xff0c;很少使用企业微信&#xff0c;对于…

C# 警告 warning MSB3884: 无法找到规则集文件“MinimumRecommendedRules.ruleset”

警告 warning MSB3884: 无法找到规则集文件“MinimumRecommendedRules.ruleset” C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\amd64\Microsoft.CSharp.CurrentVersion.targets(129,9): warning MSB3884: 无法找到规则集文件“MinimumRe…

Android Lint

文章目录 Android Lint概述工作流程Lint 问题种类Lint 警告严重性 用命令运行 LintAndroidStudio 使用 Lint忽略 Lint 警告gradle 配置 Lint查找无用资源文件 Android Lint 概述 Lint 是 Android 提供的 代码扫描分析工具&#xff0c;它可以帮助我们发现代码结构/质量问题&am…

springboot加载注入bean的方式

在SpringBoot的大环境下&#xff0c;基本上很少使用之前的xml配置Bean&#xff0c;主要是因为这种方式不好维护而且也不够方便。 springboto注入bean主要采用下图几种方式&#xff0c;分为本地服务工程注解声明的bean和外部依赖包中的bean。 一、 springboot装配本地服务工程…

国产Cortex-A55人工智能教学实验箱_基于Python机械臂跳舞实验案例分享

一、实验目的 本实验通过TL3568-PlusTEB教学实验箱修改机械臂不同舵机的角度&#xff0c;增加延迟时间&#xff0c;从而做到机械臂跳舞的效果。 二、实验原理 ROS&#xff08;机器人操作系统&#xff09; ROS&#xff08;机器人操作系统&#xff09;&#xff0c;是专为机器人…

报工计件工资核算h5开源版开发

报工计件工资核算h5开源版开发 小型计件工资管理系统&#xff0c;支持后台制定工价&#xff0c;核算工资。支持员工H5端报工&#xff0c;和查看工资情况。 H5手机端 支持在线报工&#xff0c;支持查看我的工资。 自定义费用项 在基础计件工资基础上增加扣除和增加项&#xff…

分布式服务测试各节点调用第三方服务连通性

背景&#xff1a;分布式部署 一个主节点往各个节点下发任务&#xff08;调用第三方服务&#xff09;&#xff0c;目的是为了测试各节点与第三方的连通性 思路&#xff1a; 主节点实现 创建Spring Boot项目&#xff1a;作为主节点的后端服务。 集成Eureka客户端&#xff1a;在…

Python28 十大机器学习算法之线性回归和逻辑回归

1.三类广义上的机器学习算法 监督学习。工作原理&#xff1a;该算法由一个目标/结果变量&#xff08;或因变量&#xff09;组成&#xff0c;该变量将从一组给定的预测变量&#xff08;自变量&#xff09;进行预测。使用这组变量&#xff0c;我们生成了一个将输入数据映射到所…

阿里云服务器入门使用教程——购买及操作系统选择并进行远程连接

文章目录 一、首先选择一个你自己要买的云服务器类型二、能选的就一个地域和一个操作系统&#xff0c;其他都是固定的三、创建完实例并使用finalshell连接的效果(要在完成后续步骤后才能连接)四、购买之后进入阿里云控制台&#xff0c;开通资源中心五、然后就可以看到已经帮你创…

Python数据可视化-地图可视化

1.首先绘制实现数据可视化的思维导图 具体要实现什么功能-怎么处理&#xff0c;先把思路写好 数据来源&#xff1a; 爬取的数据 运行结果&#xff1a; 部分代码&#xff1a; 完整代码请在下方↓↓↓&#x1f447;获取 转载请注明出处&#xff01;

Java设计模式系列--观察者模式写法4:注入接口

原文网址&#xff1a;Java设计模式系列--观察者模式写法4&#xff1a;注入接口-CSDN博客 简介 说明 本文用示例介绍观察者模式的写法&#xff1a;注入接口。此方法是观察者模式最好的写法 观察者模式的含义 以微信公众号为例&#xff0c;我们关注了某个微信公众号后能收到…

http/2 二进制分帧层 (Binary Framing Layer)讲解

文章目录 二进制帧HTTP/2 中的帧、消息和流1. 帧&#xff08;Frame&#xff09;2. 消息&#xff08;Message&#xff09;3. 流&#xff08;Stream&#xff09;总结示例&#xff1a; 二进制帧结构1.帧头部结构2.帧负载数据 请求和响应多路复用 链接参考&#xff1a;https://web.…

算法设计与分析--考试真题

分布式算法试题汇总选择题简答题算法题 2013级试题2019级试题2021年秋考卷 根据考试范围找相应题目做。 分布式算法试题汇总 选择题 下述说法错误的是___ A 异步系统中的消息延迟是不确定的 B 分布式算法的消息复杂性是指在所有合法的执行上发送消息总数的最大值 C 在一个异步…

深入探索Java开发世界:Redis~类型分析大揭秘

文章目录 深入探索Java开发世界&#xff1a;Redis~类型分析大揭秘一、数据结构类型二、分布式锁类型三、事物命令类型四、事物三大特性类型 深入探索Java开发世界&#xff1a;Redis~类型分析大揭秘 Redis数据库基础知识&#xff0c;类型知识点梳理~ 一、数据结构类型 Redis是一…

PHP语言学习02

好久不见&#xff0c;学如逆水行舟&#xff0c;不进则退&#xff0c;真是这样。。。突然感觉自己有点废。。。 <?php phpinfo(); ?> 新生第一个代码。 要想看到运行结果&#xff0c;打开浏览器&#xff08;127.0.0.1/start/demo01.php&#xff09; 其中&#xff0c…

揭开免费可视化工具流行背后的原因

免费可视化工具为什么越来越受欢迎&#xff1f;在大数据时代&#xff0c;数据可视化已经成为各行各业的重要工具。它不仅帮助企业和个人更直观地理解数据&#xff0c;还在决策过程中起到关键作用。尽管市场上有许多付费的数据可视化工具&#xff0c;但免费工具的受欢迎程度却在…

面试准备算法

枚举 答案肯定是字符串的某个前缀&#xff0c;然后简单直观的想法是枚举所有前缀来判断&#xff0c;设前缀长度lenz&#xff0c;前缀串的长度必然要是两个字符串长度的约数才能满足条件。 可以枚举长度&#xff0c;再去判断这个前缀串拼接若干次以后是否等于str1和str2。 cla…