Answer#
Relative paths such as assets/icon.png are resolved against the current directory, and the current directory is not where your program is. A shortcut can start it elsewhere, a terminal runs it from wherever the user is, and a double-click on an associated file starts it in another folder. The program then cannot find its own files.
std::env::current_exe() returns the path of the running executable. Its parent folder is a stable base:
use std::env;
fn main() -> std::io::Result<()> {
let exe = env::current_exe()?;
let exe_dir = exe.parent().expect("an executable always has a folder");
println!("executable name: {}", exe.file_name().unwrap().to_string_lossy());
// Files shipped beside the program are found from the executable's folder, not from the current directory,
// which is whatever folder the program was started from (a shortcut, a terminal, a file association).
let icon = exe_dir.join("assets").join("icon.png");
println!("looks for: .../{}/{}", "assets", icon.file_name().unwrap().to_string_lossy());
Ok(())
}executable name: t26.exe
looks for: .../assets/icon.png(The program was built under the name t26; the full folder is not printed, to keep a user name out of the output.)
Notes:
- Windows installer layouts: assets next to the
.exein the install folder is the common simple layout. The install folder is normally read-only for the user, so it is for files you ship, not files you write (see the settings thread). - macOS bundles: the executable is in
Contents/MacOS, and resources go inContents/Resourcesbeside it, so from the executable's folder you go up one level:exe_dir.join("../Resources/icon.png"). See the thread on the.applayout. - Compile the asset in instead: for small files (an icon, a default config)
include_bytes!("../assets/icon.png")puts the bytes inside the executable, so there is nothing to find and nothing to lose when someone copies the program alone. - Do not use it for security decisions. std's documentation lists platform-specific behaviour for
current_exeand warns against trusting it for security.
Common mistakes#
- Using paths relative to the project folder (
CARGO_MANIFEST_DIR) at run time. It is set while building, so on a user's PC it points to a folder that does not exist. It is fine for tests andinclude_bytes!. - Treating
current_exe()as infallible. It returns aResult.
Related questions#
Can I change the current directory to the executable's folder at startup?#
You can with env::set_current_dir, but it affects the whole process, including file dialogs and relative paths the user typed. Joining paths explicitly is clearer.
Sources#
- std::env::current_exe: https://doc.rust-lang.org/std/env/fn.current_exe.html (read 2026-12-05)
- std::include_bytes: https://doc.rust-lang.org/std/macro.include_bytes.html (read 2026-12-05)