std::filesystem::u8path
出自cppreference.com
在標頭 <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::string 或 std::string_view ,或空終止多字節字符串,或作為一對迭代器 [first, last) 提供。
- 若
path::value_type
是 char 且原生編碼為 UTF-8 ,則直接如同以 path(source) 或 path(first, last) 構造 path 。這是使用 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) 構造新 path
- 否則(對於非 UTF-8 窄字符編碼與非 UTF-16 wchar_t ),首先轉換 UTF-8 字符序列到 std::u32string 類型的臨時 UTF-32 編碼字符串
tmp
,然後如同用 path(tmp) 構造新 path (此 path 被採用於使用非 Unicode 多字節或單字節編碼的文件系統的 POSIX 系統上)
目錄 |
參數
source | - | UTF-8 編碼的 std::string 、 std::string_view ,指向空終止多字節字符串的指針,或指向空終止多字節字符串的以 char 為 value_type 的輸入迭代器 |
first, last | - | 一對指定 UTF-8 編碼字符序列的Template:concept |
類型要求 | ||
-InputIt 必須滿足老式輸入迭代器 (LegacyInputIterator) 。
| ||
-InputIt 的值類型必須是 char
|
返回值
將輸入字符串從 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) |
表示路徑 (類) |