You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用std::filesystem重命名文件且保留扩展名?

使用std::filesystem重命名文件并保留扩展名

当然可以用C++17引入的std::filesystem库实现,它能自动处理各种路径边缘情况(比如绝对/相对路径、跨平台路径分隔符、隐藏文件、无扩展名文件等),比手动字符串处理更可靠。

核心思路

借助std::filesystem::path类的成员函数分解路径,重新构造新文件名后执行重命名:

  1. 将原始字符串路径转换为path对象,自动适配路径格式。
  2. 通过parent_path()获取文件所在的父目录。
  3. 通过extension()获取文件的扩展名(包含前置的点,比如.txt)。
  4. 用新的基础文件名拼接扩展名,结合父目录构造新路径。
  5. 调用fs::rename()完成重命名操作。

代码示例

#include <filesystem>
#include <string>
#include <iostream>

namespace fs = std::filesystem;

void rename_file_keep_ext(const std::string& original_path, const std::string& new_base_name) {
    fs::path orig_path(original_path);
    
    // 构造新路径:父目录 / (新基础名 + 扩展名)
    fs::path new_path = orig_path.parent_path() / (new_base_name + orig_path.extension().string());
    
    try {
        fs::rename(orig_path, new_path);
    } catch (const fs::filesystem_error& e) {
        std::cerr << "重命名失败:" << e.what() << "\n";
    }
}

// 使用示例
int main() {
    // 绝对路径示例
    rename_file_keep_ext("/dir1/dir2/dir3/abc.txt", "ijk");
    // 相对路径示例
    rename_file_keep_ext("../../dir1/abc.txt", "ijk");
    // 无扩展名文件
    rename_file_keep_ext("readme", "new_readme");
    // 隐藏文件(无扩展名)
    rename_file_keep_ext(".gitignore", ".new_gitignore");
    // 多扩展名文件(比如tar.gz)
    rename_file_keep_ext("archive.tar.gz", "new_archive");
    
    return 0;
}

关键细节说明

  • path类的/运算符:自动适配不同操作系统的路径分隔符(Windows用\,Unix用/),避免手动拼接字符串的错误。
  • stem()与extension():对于test.tar.gz,stem()返回test.tar,extension()返回.gz——这是标准行为,如果需要保留整个.tar.gz作为扩展名,需额外处理(比如查找第一个点的位置),但通常场景下extension()的行为符合需求。
  • 异常处理:文件操作可能因权限不足、文件不存在、目标路径已存在等原因失败,建议用try-catch捕获filesystem_error异常,避免程序崩溃。

内容的提问来源于stack exchange,提问作者Gelly Ristor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 10:47:41