gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:07:44 39 4
gpt4 key购买 nike

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

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

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

最佳答案

PathBuf::popPathBuf::push的镜像:

Truncates self to self.parent.

Returns false and does nothing if self.file_name is None. Otherwise, returns 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 :

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

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

在你的情况下:

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

另见:

关于file - 如何只获取当前可执行文件路径的目录部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749360/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com