C++如何判断相对路径和绝对路径

在C++中,可以使用以下方法来判断一个路径是相对路径还是绝对路径:

  1. 相对路径是相对于当前工作目录的路径,而绝对路径是从根目录开始的完整路径。你可以使用std::filesystem::path类来处理路径。
cpp 复制代码
#include <iostream>
#include <filesystem>

int main() {
    std::filesystem::path path("folder/file.txt");
    
    if (path.is_relative()) {
        std::cout << "相对路径" << std::endl;
    } else {
        std::cout << "绝对路径" << std::endl;
    }
    
    return 0;
}
  1. 另一种方法是使用文件系统库中的std::filesystem::current_path()函数获取当前工作目录,并将路径与待判断的路径进行比较。
cpp 复制代码
#include <iostream>
#include <filesystem>

int main() {
    std::filesystem::path path("folder/file.txt");
    std::filesystem::path current_path = std::filesystem::current_path();
    
    if (path == current_path / path) {
        std::cout << "相对路径" << std::endl;
    } else {
        std::cout << "绝对路径" << std::endl;
    }
    
    return 0;
}

无论使用哪种方法,请确保你的编译器支持C++17或以上版本,并链接-lstdc++fs才能使用文件系统库。

相关推荐
万法若空7 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商7 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫7 小时前
C++之string(OJ练习)
开发语言·c++·stl
6Hzlia7 小时前
【Hot 100 刷题计划】 LeetCode 199. 二叉树的右视图 | C++ DFS 逆序遍历
c++·leetcode·深度优先
-Marks-8 小时前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本
CoderCodingNo9 小时前
【信奥业余科普】C++ 的奇妙之旅 | 12:程序的交互与加工——数据的输入与算术运算
开发语言·c++
yx868xy9 小时前
Cuda加速直线拟合
c++·cuda
蜗牛在听雨9 小时前
基于 C++ 的 UG/NX 二次开发环境配置
c++·二次开发·ug
SimpleLearingAI10 小时前
C++虚函数详解
开发语言·c++