std::filesystem::path::string
| template< class CharT, class Traits = std::char_traits<CharT> class Alloc = std::allocator<CharT> > std::basic_string<CharT,Traits,Alloc> string( const Alloc& a = Allocator() ) const; | (1) | (since C++17) | 
|---|---|---|
|  | (2) | (since C++17) | 
| std::string string() const; |  | |
| std::wstring wstring() const; |  | |
| std::string u8string() const; |  | |
| std::u16string u16string() const; |  | |
| std::u32string u32string() const; |  | 
以本机路径名格式返回内部路径名,转换为特定字符串类型。如果有转换,则按以下方式执行:
- 如果path::value_type是char,如果有转换,则是系统依赖的。这是典型的POSIX系统%28(如linux%29)上的情况,其中本机编码为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,转换方法未指定。
1%29所有内存分配由a...
2%29结果编码u8string()一直都是UTF-8。
参数
%280%29
返回值
本机路径名格式的内部路径名,转换为指定的字符串类型。
例外
%280%29
例
二次
#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"; // 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 APIs
    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);
    }
 
    // multibyte and wide representation can be used for output
    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二次
另见
| generic_stringgeneric_wstringgeneric_u8stringgeneric_u16stringgeneric_u32string | returns the path in generic pathname format converted to a string (public member function) | 
|---|
 © cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

