Namespaces
Variants

std::filesystem::path:: string, std::filesystem::path:: wstring, std::filesystem::path:: u8string, std::filesystem::path:: u16string, std::filesystem::path:: u32string

From cppreference.net
template < class CharT, class Traits = std:: char_traits < CharT > ,

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

string ( const Alloc & a = Alloc ( ) ) const ;
(1) (C++17以降)
(2) (C++17以降)
std:: string string ( ) const ;
std:: wstring wstring ( ) const ;
std:: u16string u16string ( ) const ;
std:: u32string u32string ( ) const ;
(3)
std:: string u8string ( ) const ;
(C++17以降)
(C++20まで)
std:: u8string u8string ( ) const ;
(C++20以降)

ネイティブのパス名形式での内部パス名を、特定の文字列型に変換して返します。変換が必要な場合は、以下のように実行されます:

  • path::value_type char の場合、変換が行われる場合はシステム依存です。これは一般的なPOSIXシステム(Linuxなど)で該当し、ネイティブエンコーディングがUTF-8であり、 string() は変換を実行しません。
  • それ以外の場合、 path::value_type wchar_t の場合、変換が行われるかどうかは未規定です。これはWindowsで該当し、 wchar_t は16ビットでネイティブエンコーディングがUTF-16です。
  • それ以外の場合、 path::value_type char16_t の場合、ネイティブエンコーディングはUTF-16であり、変換方法は未規定です。
  • それ以外の場合、 path::value_type char32_t の場合、ネイティブエンコーディングはUTF-32であり、変換方法は未規定です。
  • それ以外の場合、 path::value_type char8_t の場合、ネイティブエンコーディングはUTF-8であり、変換方法は未規定です。
1) すべてのメモリ割り当ては a によって実行されます。
3) u8string ( ) の場合の結果のエンコーディングは常にUTF-8です。

目次

パラメータ

(なし)

戻り値

ネイティブのパス名形式での内部パス名を、指定された文字列型に変換したもの。

例外

実装定義の例外をスローする可能性があります。

#include <clocale>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <locale>
int main()
{
    const char* const localeName = "ja_JP.utf-8";
    std::setlocale(LC_ALL, localeName);
    std::locale::global(std::locale(localeName));
    const std::filesystem::path p(u8"要らない.txt");
    std::ofstream(p) << "File contents";
    // ネイティブ文字列表現はOS APIで使用可能
    if (std::FILE* const f = std::fopen(p.string().c_str(), "r"))
    {
        for (int ch; (ch = std::fgetc(f)) != EOF;)
            std::putchar(ch);
        std::fclose(f);
    }
    // マルチバイトおよびワイド表現は出力に使用可能
    std::cout << "\nFile name in narrow multibyte encoding: " << p.string() << '\n';
    // wstring() will throw in stdlibc++ (as per gcc-12.1.0), see:
    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95048
    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102839
    // works with more recent gcc-12.2.1 (2023/02/01) and clang-10+
    std::wcout << "File name in wide encoding: " << p.wstring() << '\n';
    std::filesystem::remove(p);
}

出力例:

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

関連項目

汎用パス名形式に変換されたパスを文字列として返す
(公開メンバ関数)