How to get only the directory portion of the current executable's path?

瘦欲@ 提交于 2021-02-18 22:43:20

问题


I want to read files from a config folder at the directory where the executable is located. I do that using the following functions:

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()
}

In my case, get_exe_path() will return C:\Users\User\Documents\Rust\Hangman\target\debug\Hangman.exe.

With get_file_path("Config\test.txt"), I want to append Config\test.txt To the above path. Then I get the following path to the file: C:\Users\User\Documents\Rust\Hangman\target\debug\Hangman.exe\Config\test.txt

The problem is that std::env::current_exe() will get the file name of the executable also and I do not need that. I only need the directory where it is located.

Question

The following the following function call should return C:\Users\User\Documents\Rust\Hangman\target\debug\Config\test.txt:

let path = get_file_path("Config\\test.txt");

How can I get the path from the current directory without the executable name like above example? Are there any other ways to do this than using std::env::current_exe()


回答1:


PathBuf::pop is the mirror of PathBuf::push:

Truncates self to self.parent.

Returns false and does nothing if self.file_name is None. Otherwise, returns true.

In your case:

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());
}

There's also the possibility of using Path::parent:

Returns the Path without its final component, if there is one.

Returns None if the path terminates in a root or prefix.

In your case:

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)
}

See also:

  • How to get the name of current program without the directory part?


来源:https://stackoverflow.com/questions/46749360/how-to-get-only-the-directory-portion-of-the-current-executables-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!