Rust Executable cannot find files in directory

Hello, Im new to rust. I wrote a simple program that reads a json file and then displays it to the console. It works perfectly fine when I use cargo run, but when I run the executable it cannot seem to find the json file, even when its in the same directory. I know about using include_bytes! but that wraps the file with the executable so it can't be edited. I want to still be able to make changes to the file, how is this possible?

cargo run :

sets the working directory of the binary executed to the current working directory, same as if it was executed in the shell directly.

Can you show the code you're using for opening the file, so we can see how the directory is specified?

1 Like

One gotcha with cargo run vs running the executable directly is that cargo run works from any subdirectory, as well as from the project root directory. So maybe you're running cargo run from a subdirectory (where the JSON file happens to be)?

2 Likes

You can log out the current working directory of your executable like this:

use std::env::current_dir;

fn main() -> Result<(), Error> {
  dbg!(current_dir());
}

That way you should be able to see where your program is running. Using cargo run, your program will run anywhere in the project, where your JSON may be located. If you build the program and then call the executable from somwhere else, the path you are calling from becomes your CWD (current working directory). You need to put the JSON and executable in the same directory, or at least know where the JSON is located. Then you could use an absolute or relative path to get to the file

fs::read_to_string("./a.json"); // The json is in the same directory as the executable
fs::read_to_string("/home/dev/a.json"); // The json is at a known place in the FS

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.