I develop Rust program for myself. File structure is like:
src/
-main.rs
data.txt
target/
-release/
--app.exe
and main.rs contains a code let file = File::open("data.txt").unwrap();
When cargo run, program can read "data.txt" but when running exe file which is built by cargo build --release, the app can't read "data.txt" because working directory is "target/release/".
Solution I think is using cargo run always not only when developing, but it takes time to compile and it may reflects wip code.
Another is, simply moving exe file to program root directory, but if I forget to move exe file when I build again, old exe file runs.
Is there a simple way to set working directory(value of std::env::current_dir()) same for cargo run and built exe file? Must I write codes which check path includes "target/release" and std::env::set_current_dir() for all program?
In general, the working directory depends entirely on how the program was run, and you can only rely on it to be anything in particular unless you know something about how it was run.
My understanding is that for Windows, when you open an .exe file (double-clicking it or whatever), the current directory is always the directory containing the .exe, but that is not the case on the command line.
If you want your program to work with data files stored relative to it, regardless of how it was started, you should find those file by starting from current_exe() instead of the working directory.
If you want your program to be able to be installed on many platforms, then you should also be prepared to have it find files in other locations, as turns out to be needed. Different platforms have different ideas of where data files for applications are supposed to go.
I see. Maybe I should change my approach and set the working directory even during normal execution(cargo run).
Writing following three line code to all program for oneself is a bit annoying but simple solution:
let exe = std::env::current_exe().unwrap();
let working_dir = exe.parent().unwrap().parent().unwrap().parent().unwrap();//This is same exe is in "debug" dir or "release" dir
std::env::set_current_dir(working_dir).unwrap();
Most programs (whether written in Rust or not) don’t ever set the working directory. They construct absolute paths to the files they need. (Except for paths specified by a user on the command line which can be passed unchanged to the operating system whether relative or absolute).