我想从可执行文件所在目录的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()
}
就我而言,
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::pop
是PathBuf::push
的镜像:
Truncates
self
toself.parent
.Returns
false
and does nothing ifself.file_name
isNone
. Otherwise, returnstrue
.
在您的情况下:
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/66528510/