Namespaces
Variants

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

 
 
 
 
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起)
std::string string() const;
(2) (自C++17起)
std::wstring wstring() const;
(3) (自C++17起)
std::u16string u16string() const;
(4) (自C++17起)
std::u32string u32string() const;
(5) (自C++17起)
std::string u8string() const;
(6) (自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 执行。
6) 在 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";
    // 原生字符串表示可用于操作系统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() 在 stdlibc++ 中会抛出异常(基于 gcc-12.1.0),参见:
    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95048
    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102839
    // 在更新的 gcc-12.2.1 (2023/02/01) 和 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

参见

返回转换为字符串的通用路径名格式的路径
(公开成员函数)