Namespaces
Variants

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

From cppreference.net
const value_type * c_str ( ) const noexcept ;
(1) (C++17以降)
const string_type & native ( ) const noexcept ;
(2) (C++17以降)
operator string_type ( ) const ;
(3) (C++17以降)

ネイティブパス名を文字列としてアクセスします。

1) 次と同等: native ( ) . c_str ( ) .
2) パス名のネイティブ形式表現を参照で返します。
3) パス名のネイティブ形式表現を値で返します。

目次

パラメータ

(なし)

戻り値

パス名のネイティブ文字列表現。ネイティブ構文、ネイティブ文字型、ネイティブ文字エンコーディングを使用します。この文字列はOS APIでの使用に適しています。

注記

変換関数 (3) は、 std::basic_string を受け入れるAPIが、コードを変更せずにパス名を使用できるように提供されています。

#include <cstdio>
#ifdef _MSC_VER
#include <fcntl.h>
#include <io.h>
#else
#include <clocale>
#include <locale>
#endif
#include <filesystem>
#include <fstream>
int main()
{
#ifdef _MSC_VER
    _setmode(_fileno(stderr), _O_WTEXT);
#else
    std::setlocale(LC_ALL, "");
    std::locale::global(std::locale(""));
#endif
    std::filesystem::path p(u8"要らない.txt");
    std::ofstream(p) << "File contents"; // LWG2676以前はoperator string_type()を使用
                                         // MSVCではstring_typeがwstringであり、
                                         // 非標準拡張機能によってのみ動作
                                         // LWG2676以降は新しいfstreamコンストラクタを使用
    // ネイティブ文字列表現はOS固有のAPIで使用可能
#ifdef _MSC_VER
    if (std::FILE* f = _wfopen(p.c_str(), L"r"))
#else
    if (std::FILE* f = std::fopen(p.c_str(), "r"))
#endif
    {
        for (int ch; (ch = fgetc(f)) != EOF; std::putchar(ch))
        {}
        std::fclose(f);
    }
    std::filesystem::remove(p);
}

出力例:

File contents

関連項目

ネイティブパス名形式で変換された文字列としてパスを返す
(公開メンバ関数)
ジェネリックパス名形式で変換された文字列としてパスを返す
(公開メンバ関数)