std::filesystem::path::replace_extension
来自cppreference.com
| |
(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"
参阅
| 返回文件扩展名路径组分 (公开成员函数) | |
| 返回文件名路径组分 (公开成员函数) | |
| 返回主干路径组分(不带扩展名的文件名) (公开成员函数) | |
| 检查对应路径元素是否非空 (公开成员函数) |