我想从可执行文件所在目录的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
:
截断
self
为self.parent
。返回
false
,如果self.file_name
是则不执行任何操作None
。否则,返回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)
}
也可以看看:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句