如何用std::filesystem重命名文件且保留扩展名?
使用std::filesystem重命名文件并保留扩展名
当然可以用C++17引入的std::filesystem库实现,它能自动处理各种路径边缘情况(比如绝对/相对路径、跨平台路径分隔符、隐藏文件、无扩展名文件等),比手动字符串处理更可靠。
核心思路
借助std::filesystem::path类的成员函数分解路径,重新构造新文件名后执行重命名:
- 将原始字符串路径转换为
path对象,自动适配路径格式。 - 通过
parent_path()获取文件所在的父目录。 - 通过
extension()获取文件的扩展名(包含前置的点,比如.txt)。 - 用新的基础文件名拼接扩展名,结合父目录构造新路径。
- 调用
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
相关产品推荐
相关产品推荐

