std::filesystem::u8path

定义于头文件 <filesystem>
template< class Source >
path u8path( const Source& source );
(1) (C++17 起)
template< class InputIt >
path u8path( InputIt first, InputIt last );
(2) (C++17 起)

从 UTF-8 编码的 char 序列构造 path p ,源作为 std::stringstd::string_view ,或空终止多字节字符串,或作为一对迭代器 [first, last) 提供。

UTF-32),则首先转换 UTF-8 字符序列为 path::string_type 类型的临时字符串 tmp ,然后如同以 path(tmp) 构造新 path

目录

参数

source - UTF-8 编码的 std::stringstd::string_view ,指向空终止多字节字符串的指针,或指向空终止多字节字符串的以 char 为 value_type 的输入迭代器
first, last - 一对指定 UTF-8 编码字符序列的输入迭代器 (InputIterator)
类型要求
-
InputIt 必须满足 InputIterator 的要求。
-
InputIt 的 value_type 必须是 char

返回值

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

异常

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

注意

在原生路径格式异于通用路径格式的系统上( Windows 与 POSIX 均不是此种系统的例子),若此函数的参数使用通用格式,则它会被转换成原生格式。

示例

#include <cstdio>
#ifdef _MSC_VER
#include <io.h>
#include <fcntl.h>
#else
#include <locale>
#include <clocale>
#endif
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
#ifdef _MSC_VER
    _setmode(_fileno(stderr), _O_WTEXT);
#else
    std::setlocale(LC_ALL, "");
    std::locale::global(std::locale(""));
    std::cout.imbue(std::locale());
    std::wcerr.imbue(std::locale());
#endif
 
    fs::path p = fs::u8path(u8"要らない.txt");
    std::ofstream(p) << "File contents"; // 在 LWG2676 前 MSVC 上使用 operator string_type()
                                         // ,其中 string_type 是 wstring ,仅根据非标准扩展工作
                                         // LWG2676 后使用新的 fstream 构造函数
 
    // 原生字符串表示可用于 OS API
    if (std::FILE* f =
#ifdef _MSC_VER
                _wfopen(p.c_str(), L"r")
#else
                std::fopen(p.c_str(), "r")
#endif
        )
    {
        int ch;
        while((ch=fgetc(f))!= EOF) putchar(ch);
        std::fclose(f);
    }
 
    // 多字节与宽字节表示可用于输出
    std::cout << "\nFile name in narrow multibyte encoding: " << p.string() << '\n';
    std::wcerr << "File name in wide encoding: " << p.wstring() << '\n';
 
    fs::remove(p);
}

输出:

File contents
File name in narrow multibyte encoding: 要らない.txt
File name in wide encoding: 要らない.txt

参阅

(C++17)
表示一个路径
(类)

版本历史

  • (当前 | 先前 2017年5月1日 (一) 03:32Fruderica讨论 | 贡献 . . (2,516字节) (+18). . (撤销)
  • 当前 | 先前) 2017年5月1日 (一) 03:31Fruderica讨论 | 贡献. . (2,498字节) (+2,498). . (以“{{cpp/filesystem/title|u8path}} {{cpp/filesystem/path/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | num=1 | since=c++17 | 1= template< class Source > pa...”为内容创建页面)