1
votes

I have text file templates that I need to read, modify, then save to the user's directory in my cli app. The problem is that I don't know how to read these template files from my Rust app directory.

File Structure

- src
  - templates
    - foo.txt
    - bar.txt
  - main.rs

So in my main.rs, I would like to read the contents of foo.txt from the templates directory, modify the contents as a string, and then write it to the directory that the user is running the cli app from.

I've tried to read the files using:

std::fs::read_to_string("./templates/foo.txt").unwrap();

but since it's relative to where the user is running the cli app from, it doesn't exist there.

I've read about std::env::current_exe but it has a few warnings and looks like it might not be consistent so I'm not sure if this is the best way to do it.

1
This will always depend on the current working directory anyway. The alternative here is embedding these files in (or with) the application itself, for instance using the std::include_str macro. - michaeldel
You can use current_exe if you want to design your application this way. Alternatively you could always put your configuration/template files relative to home_dir(). - Yidaotus
@Yidaotus it looks like std::env::home_dir is deprecated. - Mr.Smithyyy
@Mr.Smithyyy use the dirs crate instead - vallentin

1 Answers

1
votes

What you're looking for is std::env::current_dir: Docs.rs This returns a PathBuf for the current working directory.