【问题标题】:How to get only the directory portion of the current executable's path?如何仅获取当前可执行文件路径的目录部分?
【发布时间】:2018-03-26 17:42:24
【问题描述】:

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

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

就我而言,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");

我如何从当前目录获取路径,而不像上面的示例那样包含可执行文件名称?除了使用std::env::current_exe()

,还有其他方法可以做到这一点吗?

【问题讨论】:

    标签: file path directory rust


    【解决方案1】:

    PathBuf::popPathBuf::push的镜像:

    self 截断为self.parent

    返回false,如果self.file_nameNone,则不执行任何操作。否则, 返回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());
    }
    

    还有可能使用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)
    }
    

    另见:

    【讨论】:

    • PathBuf::pop 的文档现在说:“将 self 截断为 self.parent。如果 self.parent 为 None,则返回 false 并且不执行任何操作。否则,返回 true。”这与这个答案所引用的不同(我猜来自旧文档),它说“如果 self.file_name 是 None 什么都不做”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2018-10-17
    • 2017-04-16
    • 2019-02-18
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多