Closed wscheff42 closed 8 months ago
Does this work when the tool is started using cargo, ie cargo r
?
Yes, it works. But you have to copy the config.toml file to the /target/debug dir. (tested with Raspbian 10 (buster))
K, thanks for the update. I'll think of a backwards compatible way, too.
Hi,
Here you can find a proposal, checking first in calling dir, and if not available, checking in path of execution (currently not tested)
use std::fs;
use std::path::{Path, PathBuf};
fn main() {
// Check in the current directory
let current_dir_path = Path::new("config.toml");
if current_dir_path.exists() {
let contents = fs::read_to_string(current_dir_path).expect("Could not read config.toml from current directory");
// Rest of your code using 'contents' variable
} else {
// Check in the path of the main program
let mut path = std::env::current_exe().expect("Unable to get current executable path");
path.pop(); // Remove executable name
path.push("config.toml");
if path.exists() {
let contents = fs::read_to_string(&path).expect("Could not read config.toml from main program path");
// Rest of your code using 'contents' variable
} else {
eprintln!("Error: config.toml not found in current directory or main program path");
}
}
}
The config.toml file can only be read, if it's in the executed directory. if you try to call the program from other directory in e.g. /usr/bin, the program stops with an error. Following code for main.rs establish program to read config.toml in the same directory as the executable file is: