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

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::string u8string() const;
std::u16string u16string() const;
std::u32string u32string() const;

返回原生路径名格式的内部路径名,转换到指定的字符串类型。若存在转换,则按下列方式进行:

1) 所有内存分配由 a 进行。
2) u8string() 情形的编码结果始终是 UTF-8 。

目录

参数

(无)

返回值

转换到指定字符串类型的原生路径名格式的内部路径名。

异常

(无)

示例

#include <cstdio>
#ifdef _MSC_VER
#include <io.h>
#include <fcntl.h>
#else
#include <locale>
#include <clocale>
#endif
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
#ifdef _MSC_VER
    _setmode(_fileno(stderr), _O_WTEXT);
#else
    std::setlocale(LC_ALL, "");
    std::locale::global(std::locale(""));
    std::cout.imbue(std::locale());
    std::wcerr.imbue(std::locale());
#endif
 
    fs::path p = fs::u8path(u8"要らない.txt");
    std::ofstream(p) << "File contents"; // 在 LWG2676 前 MSVC 上使用 operator string_type()
                                         // ,其中 string_type 是 wstring ,仅根据非标准扩展工作
                                         // LWG2676 后使用新的 fstream 构造函数
 
    // 原生字符串表示可用于 OS API
    if (std::FILE* f =
#ifdef _MSC_VER
                _wfopen(p.c_str(), L"r")
#else
                std::fopen(p.c_str(), "r")
#endif
        )
    {
        int ch;
        while((ch=fgetc(f))!= EOF) putchar(ch);
        std::fclose(f);
    }
 
    // 多字节与宽字节表示可用于输出
    std::cout << "\nFile name in narrow multibyte encoding: " << p.string() << '\n';
    std::wcerr << "File name in wide encoding: " << p.wstring() << '\n';
 
    fs::remove(p);
}

输出:

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

参阅

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

版本历史

  • (当前 | 先前 2017年12月7日 (四) 04:38D41D8CD98F讨论 | 贡献. . (1,212字节) (-3). . (撤销)
  • 当前 | 先前) 2017年5月1日 (一) 06:03Fruderica讨论 | 贡献. . (1,215字节) (+1,215). . (以“{{cpp/filesystem/path/title|string|wstring|u8string|u16string|u32string}} {{cpp/filesystem/path/navbar}} {{dcl begin}} {{dcl | num=1 | since=c++17 | 1= template< cla...”为内容创建页面)