命名空间
变体
操作

std::filesystem::current_path

来自 cppreference.cn
 
 
 
定义于头文件 <filesystem>
path current_path();
(1) (自 C++17 起)
path current_path( std::error_code& ec );
(2) (自 C++17 起)
void current_path( const std::filesystem::path& p );
(3) (自 C++17 起)
void current_path( const std::filesystem::path& p,
                   std::error_code& ec ) noexcept;
(4) (自 C++17 起)

返回或更改当前路径。

1,2) 返回当前工作目录的绝对路径,如同通过 POSIX getcwd(以原生格式)获得。(2) 若发生错误则返回 path()
3,4) 将当前工作目录更改为 p,如同通过 POSIX chdir

目录

[编辑] 参数

p - 要将当前工作目录更改为的路径
ec - 用于在非抛出重载中报告错误的输出参数

[编辑] 返回值

1,2) 返回当前工作目录。
3,4) (无)

[编辑] 异常

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

1) 在底层 OS API 错误时抛出 std::filesystem::filesystem_error,并以 OS 错误代码作为错误代码实参构造。
2) 若 OS API 调用失败,则将 std::error_code& 形参设为 OS API 错误代码,且若无错误发生则执行 ec.clear()
3) 在底层 OS API 错误时抛出 std::filesystem::filesystem_error,并以 p 作为首个路径实参,而以 OS 错误代码作为错误代码实参构造。
4) 若 OS API 调用失败,则将 std::error_code& 形参设为 OS API 错误代码,且若无错误发生则执行 ec.clear()

[编辑] 注解

当前工作目录是与进程关联的目录,它被用作相对路径的路径名解析的起始位置。

许多操作系统返回的当前路径是一个危险的全局变量。它可能被第三方或系统库函数,或另一个线程意外更改。

[编辑] 示例

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
 
int main()
{
    std::cout << "Current path is " << fs::current_path() << '\n'; // (1)
    fs::current_path(fs::temp_directory_path()); // (3)
    std::cout << "Current path is " << fs::current_path() << '\n';
}

可能的输出

Current path is "D:/local/ConsoleApplication1"
Current path is "E:/Temp"

[编辑] 参见

返回适合临时文件的目录
(函数) [编辑]