std::filesystem::u8path
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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) |
| 类型要求 | ||
-InputIt 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
-Source 或 InputIt 的值类型必须是 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) << "文件内容"; // 在 LWG2676 前的 MSVC 上使用 operator string_type(),
// 其中 string_type 是 wstring,仅根据非标准扩展工作。
// LWG2676 后使用新的 fstream 构造函数
// 原生字符串表示可用于 OS 专有 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);
}
可能的输出:
文件内容
参阅
(C++17) |
表示路径 (类) |