Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

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

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:UsersUserDocumentsRustHangmanargetdebugHangman.exe.

With get_file_path("Configest.txt"), I want to append Configest.txt To the above path. Then I get the following path to the file: C:UsersUserDocumentsRustHangmanargetdebugHangman.exeConfigest.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:UsersUserDocumentsRustHangmanargetdebugConfigest.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()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...