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才能使用文件系统库。

相关推荐
m0_706653231 天前
模板编译期排序算法
开发语言·c++·算法
历程里程碑1 天前
Linxu14 进程一
linux·c语言·开发语言·数据结构·c++·笔记·算法
m0_561359671 天前
嵌入式C++加密库
开发语言·c++·算法
近津薪荼1 天前
优选算法——双指针专题7(单调性)
c++·学习·算法
JiL 奥1 天前
Nexus制品归档(c/c++项目)
c语言·c++
j445566111 天前
C++中的职责链模式实战
开发语言·c++·算法
m0_686041611 天前
实时数据流处理
开发语言·c++·算法
知无不研1 天前
内存碎片与内存优化
开发语言·c++·内存优化·内存碎片·内存操作
m0_561359671 天前
C++模块接口设计
开发语言·c++·算法
从此不归路1 天前
Qt5 进阶【11】图形视图框架:用 QGraphicsView 搭一个流程图编辑器
开发语言·c++·qt