std::filesystem::u8path
來自 cppreference.com
< 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 編碼的 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) << "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) |
表示一個路徑 (類) |