相关疑难解决方法(0)

用于从Rust中的给定路径中提取文件扩展名

我试图从给定的String路径中提取文件的扩展名.

下面这段代码可以工作,但我想知道是否有一个更干净,更惯用的Rust方法来实现这个目的:

use std::path::Path;

fn main() {

    fn get_extension_from_filename(filename: String) -> String {

        //Change it to a canonical file path.
        let path = Path::new(&filename).canonicalize().expect(
            "Expecting an existing filename",
        );

        let filepath = path.to_str();
        let name = filepath.unwrap().split('/');
        let names: Vec<&str> = name.collect();
        let extension = names.last().expect("File extension can not be read.");
        let extens: Vec<&str> = extension.split(".").collect();

        extens[1..(extens.len())].join(".").to_string()
    }

    assert_eq!(get_extension_from_filename("abc.tar.gz".to_string()) ,"tar.gz" );
    assert_eq!(get_extension_from_filename("abc..gz".to_string()) ,".gz" );
    assert_eq!(get_extension_from_filename("abc.gz".to_string()) , "gz");

}
Run Code Online (Sandbox Code Playgroud)

filenames file-extension path rust

7
推荐指数
2
解决办法
2378
查看次数

如何仅获取当前可执行文件路径的目录部分?

我想从可执行文件所在目录的 config 文件夹中读取文件。我使用以下功能来做到这一点:

use std::env;

// add part of path to te path gotten from fn get_exe_path();
fn get_file_path(path_to_file: &str) -> PathBuf {
    let final_path = match get_exe_path() {
        Ok(mut path) => {
            path.push(path_to_file);
            path
        }
        Err(err) => panic!("Path does not exists"),
    };
    final_path
}

// Get path to current executable
fn get_exe_path() -> Result<PathBuf, io::Error> {
    //std::env::current_exe()
    env::current_exe()
}
Run Code Online (Sandbox Code Playgroud)

就我而言,get_exe_path()将返回C:\Users\User\Documents\Rust\Hangman\target\debug\Hangman.exe

随着get_file_path("Config\test.txt"),我想附加Config\test.txt到上述路径。然后我得到文件的以下路径:C:\Users\User\Documents\Rust\Hangman\target\debug\Hangman.exe\Config\test.txt

问题是它std::env::current_exe()也会获得可执行文件的文件名,而我不需要那个。我只需要它所在的目录。

以下函数调用应返回C:\Users\User\Documents\Rust\Hangman\target\debug\Config\test.txt

let path …
Run Code Online (Sandbox Code Playgroud)

directory file path rust

7
推荐指数
1
解决办法
7001
查看次数

在 Rust 中根据另一个路径格式化文件名的最佳方法

下面有更简洁的写法吗?

use std::path::Path;

let path = Path::new("/path/to/foo.txt");
let formatted = &format!("{}%d.{}", path.file_stem().unwrap().to_str().unwrap(), path.extension().unwrap().to_str().unwrap());

assert_eq!("foo%d.txt", formatted);
Run Code Online (Sandbox Code Playgroud)

(我想转换/path/to/foo.txtfoo%d.txt

string path rust

2
推荐指数
1
解决办法
2510
查看次数

替换Rust中的路径部分

假设我有以下三条路径:

let file = path::Path::new("/home/meurer/test/a/01/foo.txt");
let src = path::Path::new("/home/meurer/test/a");
let dst = path::Path::new("/home/meurer/test/b");
Run Code Online (Sandbox Code Playgroud)

现在,我想复制filedst,但为此我需要更正路径,以便我可以new_file使用解析的路径/home/meurer/test/b/01/foo.txt.换句话说,如何src从中删除file然后将结果附加到dst

/home/meurer/test/a/01/foo.txt - > /home/meurer/test/b/01/foo.txt

请注意,我们不能假设src总是这样dst.

formatting replace path rust

2
推荐指数
1
解决办法
175
查看次数

如何替换 PathBuf 或 Path 的文件扩展名?

我目前的解决方案是:

let temp = format!(
    "{}.png",
    path.file_stem().unwrap().to_string_lossy());
path.pop();
path.push(&temp);
Run Code Online (Sandbox Code Playgroud)

这很丑陋,需要至少 6 个函数调用并创建一个新字符串。

有没有更惯用、更短或更有效的方法来做到这一点?

path rust

1
推荐指数
1
解决办法
844
查看次数

标签 统计

path ×5

rust ×5

directory ×1

file ×1

file-extension ×1

filenames ×1

formatting ×1

replace ×1

string ×1