命名空间
变体
操作

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 编码的 charchar8_t(C++20 起) 序列构造一个路径 p,该序列可以是一个 std::string、一个 std::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 编码字符序列的遗留输入迭代器 (LegacyInputIterator)
类型要求
-
InputIt 必须满足 LegacyInputIterator 的要求。
-
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)
表示一个路径
(类) [编辑]