home ~ socials ~ projects ~ rss

Change the Working Directory of a Rust App

September 2025

Use std::env::set_current_dir() to change the working directory of an app like cd on the command line:

use std::env;
use std::path::PathBuf;

fn main() -> Result<(), std::io::Error> {
  let target_dir = PathBuf::from("/Users/alan/Desktop");
  match env::set_current_dir(target_dir) {
    Ok(_) => {
      println!("successfully changed directory");
    },
    Err(error) => {
      println!("{}", error);
    }
  }
  Ok(())
}
Output:
successfully changed directory
end of line
Share link:
https://www.alanwsmith.com/en/32/d6/5m/mo/?change-the-working-directory-of-a-rust-app