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

Tim*_*ost 7 directory file path rust

我想从可执行文件所在目录的 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 = get_file_path("Config\\test.txt");
Run Code Online (Sandbox Code Playgroud)

如何从当前目录获取路径而不像上面的示例那样具有可执行文件名称?除了使用,还有其他方法可以做到这一点吗std::env::current_exe()

She*_*ter 13

PathBuf::pop是镜子PathBuf::push:

截断self为self.parent。

false如果self.file_nameis ,则返回并且不执行任何操作None。否则,返回true。

在你的情况下:

use std::env;
use std::io;
use std::path::PathBuf;

fn inner_main() -> io::Result<PathBuf> {
    let mut dir = env::current_exe()?;
    dir.pop();
    dir.push("Config");
    dir.push("test.txt");
    Ok(dir)
}

fn main() {
    let path = inner_main().expect("Couldn't");
    println!("{}", path.display());
}
Run Code Online (Sandbox Code Playgroud)

还有可能使用Path::parent:

Path如果有,则返回没有其最终组件的 。

返回None路径是否以根或前缀结尾。

在你的情况下:

fn inner_main() -> io::Result<PathBuf> {
    let exe = env::current_exe()?;
    let dir = exe.parent().expect("Executable must be in some directory");
    let mut dir = dir.join("Config");
    dir.push("test.txt");
    Ok(dir)
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: