名稱空間
變體
操作

std::filesystem::path::generic_string, std::filesystem::path::generic_wstring, std::filesystem::path::generic_u8string, std::filesystem::path::generic_u16string, std::filesystem::path::generic_u32string

來自 cppreference.com
< cpp‎ | filesystem‎ | path
 
 
 
 
template< class CharT, class Traits = std::char_traits<CharT>,

          class Alloc = std::allocator<CharT> >
std::basic_string<CharT,Traits,Alloc>

    generic_string( const Alloc& a = Alloc() ) const;
(1) (C++17 起)
(2) (C++17 起)
std::string generic_string() const;
std::wstring generic_wstring() const;
std::u16string generic_u16string() const;
std::u32string generic_u32string() const;
(3)
std::string generic_u8string() const;
(C++17 起)
(C++20 前)
std::u8string generic_u8string() const;
(C++20 起)

以通用路徑名格式返回內部路徑名,並轉換為特定的字串型別。如果進行轉換,則指定如下:

  • 如果 path::value_typechar,則轉換(如果有)是系統相關的。這在典型的 POSIX 系統(如 Linux)上是這種情況,其中本機編碼是 UTF-8,並且 string() 不執行任何轉換。
  • 否則,如果 path::value_typewchar_t,則轉換(如果有)是未指定的。這在 Windows 上是這種情況,其中 wchar_t 是 16 位,本機編碼是 UTF-16。
  • 否則,如果 path::value_typechar16_t,則本機編碼是 UTF-16,轉換方法未指定。
  • 否則,如果 path::value_typechar32_t,則本機編碼是 UTF-32,轉換方法未指定。
  • 否則,如果 path::value_typechar8_t,則本機編碼是 UTF-8,轉換方法未指定。

使用 / 字元作為目錄分隔符。

1) 所有記憶體分配都由 a 執行。
3)u8string() 的情況下,結果編碼始終是 UTF-8。

目錄

[edit] 引數

a - 用於構造字串的分配器
型別要求
-
CharT 必須是編碼字元型別之一(charwchar_tchar8_t(C++20 起)char16_tchar32_t)。

[edit] 返回值

以通用路徑名格式表示的內部路徑名,轉換為指定的字串型別。

[編輯] 異常

可能丟擲實現定義的異常。

[edit] 示例

#include <cstddef>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <span>
#include <string_view>
 
void print(std::string_view rem, auto const& str)
{
    std::cout << rem << std::hex << std::uppercase << std::setfill('0');
    for (const auto b : std::as_bytes(std::span{str}))
        std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' ';
    std::cout << '\n';
}
 
int main()
{
    std::filesystem::path p{"/家/屋"};
    std::cout << p << '\n';
 
    print("string    : ", p.generic_string());
    print("u8string  : ", p.generic_u8string());
    print("u16string : ", p.generic_u16string());
    print("u32string : ", p.generic_u32string());
    print("wstring   : ", p.generic_wstring());
}

可能的輸出

"/家/屋"
string    : 2F E5 AE B6 2F E5 B1 8B
u8string  : 2F E5 AE B6 2F E5 B1 8B
u16string : 2F 00 B6 5B 2F 00 4B 5C
u32string : 2F 00 00 00 B6 5B 00 00 2F 00 00 00 4B 5C 00 00
wstring   : 2F 00 00 00 B6 5B 00 00 2F 00 00 00 4B 5C 00 00

[edit] 另請參閱

返回轉換為字串的原生路徑名格式的路徑
(public member function) [edit]