命名空间
变体
操作

std::filesystem::u8path

来自 cppreference.cn
< cpp‎ | filesystem‎ | path
 
 
 
 
定义于头文件 <filesystem>
template< class Source >
std::filesystem::path u8path( const Source& source );
(1) (C++17 起)
(C++20 中已弃用)
template< class InputIt >
std::filesystem::path u8path( InputIt first, InputIt last );
(2) (C++17 起)
(C++20 中已弃用)

从 UTF-8 编码的 char 序列(char8_t 序列(C++20 起))构造路径 p,序列可以作为 std::stringstd::string_view、空终止多字节字符串或 [first, last) 迭代器对提供。

  • 如果 path::value_typechar 且原生编码为 UTF-8,则直接构造路径,如同通过 path(source)path(first, last)。注意:这是使用 Unicode 的 POSIX 系统的典型情况,例如 Linux。
  • 否则,如果 path::value_typewchar_t 且原生编码为 UTF-16(这是 Windows 上的情况),或者如果 path::value_typechar16_t (原生编码保证为 UTF-16)或 char32_t (原生编码保证为 UTF-32),则首先将 UTF-8 字符序列转换为类型为 path::string_type 的临时字符串 tmp,然后如同通过 path(tmp) 构造新路径。
  • 否则(对于非 UTF-8 窄字符编码和非 UTF-16 wchar_t),首先将 UTF-8 字符序列转换为类型为 std::u32string 的临时 UTF-32 编码字符串 tmp,然后如同通过 path(tmp) 构造新路径(在具有非 Unicode 多字节或单字节编码文件系统的 POSIX 系统上采用此路径)。

内容

[编辑] 参数

source - UTF-8 编码的 std::stringstd::string_view、指向空终止多字节字符串的指针,或具有 char 值类型的输入迭代器,指向空终止多字节字符串
first, last - 指定 UTF-8 编码字符序列的 旧式输入迭代器
类型要求
-
InputIt 必须满足旧式输入迭代器 的要求。
-
SourceInputIt 的值类型必须是 char char8_t(C++20 起)

[编辑] 返回值

从输入字符串转换 UTF-8 到文件系统的原生字符编码后构造的路径。

[编辑] 异常

若内存分配失败,可能抛出 std::bad_alloc

[编辑] 注解

在原生路径格式与通用路径格式不同的系统上(Windows 和 POSIX 系统都不是这种操作系统的示例),如果此函数的参数使用通用格式,它将被转换为原生格式。

[编辑] 示例

#include <cstdio>
#ifdef _MSC_VER
#include <fcntl.h>
#include <io.h>
#else
#include <clocale>
#include <locale>
#endif
#include <filesystem>
#include <fstream>
 
int main()
{
#ifdef _MSC_VER
    _setmode(_fileno(stderr), _O_WTEXT);
#else
    std::setlocale(LC_ALL, "");
    std::locale::global(std::locale(""));
#endif
 
    std::filesystem::path p(u8"要らない.txt");
    std::ofstream(p) << "File contents"; // Prior to LWG2676 uses operator string_type()
                                         // on MSVC, where string_type is wstring, only
                                         // works due to non-standard extension.
                                         // Post-LWG2676 uses new fstream constructors
 
    // Native string representation can be used with OS-specific APIs
#ifdef _MSC_VER
    if (std::FILE* f = _wfopen(p.c_str(), L"r"))
#else
    if (std::FILE* f = std::fopen(p.c_str(), "r"))
#endif
    {
        for (int ch; (ch = fgetc(f)) != EOF; std::putchar(ch))
        {}
        std::fclose(f);
    }
 
    std::filesystem::remove(p);
}

可能的输出

File contents

[编辑] 参见

(C++17)
表示路径
(类) [编辑]