std::experimental::filesystem::path::c_str, std::experimental::filesystem::path::native, std::experimental::filesystem::path::operator string_type()

< cpp‎ | experimental‎ | fs‎ | path
const value_type* c_str() const;
(1) (文件系统 TS)
const string_type& native() const;
(2) (文件系统 TS)
operator string_type() const;
(3) (文件系统 TS)

以字符串的形式访问原生路径名。

1) 等价于 native().c_str()
2) 按引用返回路径名的原生字符串表示。
3) 按值返回路径名的原生字符串表示。

参数

(无)

返回值

路径名的原生字符串表示,使用原生语法,原生字符类型,和原生字符编码。此字符串适用于 OS API。

异常

1,2)
noexcept 规定:  
noexcept
  

注解

提供转换函数 (3),以使接受 std::basic_string 文件名的标准文件打开 API,如 std::ifstream 构造函数,可以使用路径名而无需改动代码:

fs::path p = "/tmp/text.txt";
std::ifstream f(p);

示例

#include <clocale>
#include <cstdio>
#include <experimental/filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::experimental::filesystem;
 
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    std::locale::global(std::locale("en_US.utf8"));
 
    fs::path p = fs::u8path(u8"要らない.txt");
 
    // 原生字符串表示可以与 OS API 一起使用
    std::ofstream(p) << "文件内容"; // 这里使用 operator string()
    if (std::FILE* f = std::fopen(p.c_str(), "r"))
    {
        int ch;
        while ((ch=fgetc(f))!= EOF) putchar(ch);
        std::fclose(f);
    }
 
    // 多字节和宽字节表示可以用于输出
    std::cout.imbue(std::locale());
    std::cout << "\n窄多字节编码的文件名:"
              << p.string() << '\n';
 
    std::wcerr.imbue(std::locale());
    std::wcerr << "宽编码的文件名:"
               << p.wstring() << '\n';
 
    fs::remove(p);
}

可能的输出:

文件内容
窄多字节编码的文件名:要らない.txt
宽编码的文件名:要らない.txt

参阅

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