名稱空間
變體
操作

std::filesystem::path::replace_extension

來自 cppreference.com
< cpp‎ | filesystem‎ | path
 
 
 
 
path& replace_extension( const path& replacement = path() );
(C++17 起)

替換副檔名,使用 replacement 指定的副檔名;若使用 replacement 的預設值則移除副檔名。

首先,若此路徑擁有 extension(),則從路徑名的通用格式檢視中移除它。

然後,若 replacement 非空且不以點字元開頭,則在路徑名的通用格式檢視後追加一個點字元。

然後,如同透過 operator+=(replacement) 般,追加 replacement

目錄

[編輯] 引數

replacement - 用於替換的副檔名

[編輯] 返回值

*this

[編輯] 異常

可能丟擲實現定義的異常。

[編輯] 注意

replacement 的型別是 std::filesystem::path,儘管它不意圖表示檔案系統上的物件,以正確處理檔案系統字元編碼。

[編輯] 示例

#include <filesystem>
#include <iomanip>
#include <iostream>
#include <utility>
 
int main()
{
    const int width1{18}, width2{11}; // columns' width
 
    std::cout << std::left << std::setw(width1) << "Path:"
              << std::setw(width2) << "Ext:" << "Result:\n";
    for (const auto& [p, e] : {
            std::make_pair("/foo/bar.jpg", ".png"),
            {"/foo/bar.jpg", "png"},
            {"/foo/bar.jpg", "."},
            {"/foo/bar.jpg", ""},
            {"/foo/bar.", "png"},
            {"/foo/bar", ".png"},
            {"/foo/bar", "png"},
            {"/foo/bar", "."},
            {"/foo/bar", ""},
            {"/foo/.", ".png"},
            {"/foo/.", "png"},
            {"/foo/.", "."},
            {"/foo/.", ""},
            {"/foo/", ".png"},
            {"/foo/", "png"}})
    {
        std::filesystem::path path{p}, ext{e};
        std::cout << std::setw(width1) << path << std::setw(width2) << ext;
        path.replace_extension(ext);
        std::cout << path << '\n';
    }
}

輸出

Path:             Ext:       Result:
"/foo/bar.jpg"    ".png"     "/foo/bar.png"
"/foo/bar.jpg"    "png"      "/foo/bar.png"
"/foo/bar.jpg"    "."        "/foo/bar."
"/foo/bar.jpg"    ""         "/foo/bar"
"/foo/bar."       "png"      "/foo/bar.png"
"/foo/bar"        ".png"     "/foo/bar.png"
"/foo/bar"        "png"      "/foo/bar.png"
"/foo/bar"        "."        "/foo/bar."
"/foo/bar"        ""         "/foo/bar"
"/foo/."          ".png"     "/foo/..png"
"/foo/."          "png"      "/foo/..png"
"/foo/."          "."        "/foo/.."
"/foo/."          ""         "/foo/."
"/foo/"           ".png"     "/foo/.png"
"/foo/"           "png"      "/foo/.png"

[編輯] 參閱

返回副檔名路徑元件
(公共成員函式) [編輯]
返回檔名路徑元件
(公共成員函式) [編輯]
返回主檔名路徑元件(不帶最終副檔名的檔名)
(公共成員函式) [編輯]
檢查相應路徑元素是否不為空
(公開成員函式)