Namespaces
Variants

std::filesystem:: u8path

From cppreference.net
定义于头文件 <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::string std::string_view 、以空字符结尾的多字节字符串,或者是 [ first, last ) 迭代器对。

  • path::value_type char 且原生编码为 UTF-8,则直接构造路径,如同通过 path ( source ) path ( first, last ) 构造。注意:这是使用 Unicode 的 POSIX 系统(如 Linux)的典型情况。
  • 否则,若 path::value_type wchar_t 且原生编码为 UTF-16(此为 Windows 系统的情况),或 path::value_type char16_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::string std::string_view ,指向以空字符结尾的多字节字符串的指针,或指向以空字符结尾的多字节字符串的 char 值类型输入迭代器
first, last - 指定 UTF-8 编码字符序列的 LegacyInputIterator s
类型要求
-
InputIt 必须满足 LegacyInputIterator 的要求。
-
Source InputIt 的值类型必须为 char char8_t (since 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"; // LWG2676 之前使用 operator string_type()
                                         // 在 MSVC 上,其中 string_type 是 wstring,
                                         // 仅因非标准扩展而有效。
                                         // LWG2676 之后使用新的 fstream 构造函数
    // 原生字符串表示可用于操作系统特定 API
#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)
表示路径
(类)