Getting the absolute path for an binary: Can this be improved?

Hi,

I am trying to get the absolute path of my executable as there are some resources present in the run-time directory. The reason for this is I want to allow the binary to read in the resource file when it is executed from any directory.

Generally I set up my environment as follows (crudely stated):
PATH += /path/to/executable/release/

/path/to/executable/
├───src
└───release
        ├───settings.ini
        └───binary

cd /path/elsewhere/
$ binary

I've written the following code which is executed during run-time. It obtains the absolute path for the executable, including the binary name itself, and then strips off the end to remove the binary name. The longer I stare at it the more I think it could be written a lot better.

Are there any suggestions on how this could be done better?

match env::current_exe() {
	Ok(exe_path) => {
		let exe_path_str = exe_path.display().to_string();

		let mut abs_path_vec : Vec<&str> = exe_path_str.split("\\").collect();
		assert!(abs_path_vec.len() > 0);
		let len = abs_path_vec.len() - 1;
		let abs_path : String = abs_path_vec.drain(0..len).collect::<Vec<_>>().join("\\");
		format!("{}{}", abs_path, "\\settings.ini")
	},
	Err(e) => String::from(""),
}

1 Like

Not at my PC, but it looks like PathBuf, the type of exe_path has some methods that you might find helpful.

Heck, even better!

2 Likes

That looks like it does exactly what I need without all of the chaos listed above. Thanks!