Read file from application directory in cli app

Viewed 327

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 Answers

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

Related