Namespaces
Variants

std::filesystem:: absolute

From cppreference.net
定义于头文件 <filesystem>
path absolute ( const std:: filesystem :: path & p ) ;
(1) (C++17 起)
path absolute ( const std:: filesystem :: path & p, std:: error_code & ec ) ;
(2) (C++17 起)

返回一个引用与 p 相同文件系统位置的路径,该路径满足 filesystem::path::is_absolute() true

2) 此不抛出异常的版本在发生错误时返回默认构造的 path。

目录

参数

p - 要转换为绝对形式的路径
ec - 非抛出重载中用于错误报告的输出参数

返回值

返回一个引用与 p 相同文件的绝对(但不一定是规范)路径名。

异常

任何未标记为 noexcept 的重载在内存分配失败时可能抛出 std::bad_alloc

1) 当底层操作系统 API 出错时抛出 std::filesystem::filesystem_error ,该异常以 p 作为第一个路径参数,以操作系统错误代码作为错误码参数构造。
2) 若操作系统API调用失败,将 std:: error_code & 参数设置为操作系统API错误码;若无错误发生,则执行 ec. clear ( )

注释

实现方应避免将 p 不存在的情况视为错误。

对于基于POSIX的操作系统, std :: filesystem :: absolute ( p ) 等同于 std:: filesystem :: current_path ( ) / p ,除非当 p 为空路径时。

对于 Windows 系统, std::filesystem::absolute 可能通过调用 GetFullPathNameW 来实现。

示例

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main()
{
    std::filesystem::path p = "foo.c";
    std::cout << "当前路径为 " << std::filesystem::current_path() << '\n';
    std::cout << "文件 " << p << " 的绝对路径为 " << fs::absolute(p) << '\n';
}

可能的输出:

当前路径为 "/tmp/1666297965.0051296"
文件 "foo.c" 的绝对路径为 "/tmp/1666297965.0051296/foo.c"

参见

组合规范路径
(函数)
组合相对路径
(函数)