简体   繁体   English

如何更改路径的文件名而不更改其目录或扩展名?

[英]How do I change the file name of a path without changing its directory or extension?

What's the best way to implement the change_file_name function?实现change_file_name function 的最佳方法是什么?

let path = Path::new("/path/to/file.rs");
let new_path = change_file_name(&path, "new_file_name") // -> "/path/to/new_file_name.rs"

Take something that can be referenced as a Path , then pop off the existing filename, replacing it and preserving the optional extension:取一些可以作为Path引用的东西,然后弹出现有的文件名,替换它并保留可选的扩展名:

use std::path::{Path, PathBuf};

fn change_file_name(path: impl AsRef<Path>, name: &str) -> PathBuf {
    let path = path.as_ref();
    let mut result = path.to_owned();
    result.set_file_name(name);
    if let Some(ext) = path.extension() {
        result.set_extension(ext);
    }
    result
}

fn main() {
    let path = "/path/to/file.rs";
    let new_path = change_file_name(path, "new_file_name");
    assert_eq!(new_path, Path::new("/path/to/new_file_name.rs"));
}

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM