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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…