rustdirectory

How to create a folder outside the project directory in Rust?


I'm using Rust to create a folder in ~, however when my code runs the directory is created inside my project's folder instead in ~.

My code:

use std::fs::create_dir_all;
use std::path::Path;

fn main() {
    let path = Path::new("~/.hidden_folder");
    match create_dir_all(path) {
        Ok(f) => {
            println!("created folder")
        },
        Err(err) => {
            println!("{:?}", err);
        }
    };
}

Any idea how to create the folder in the correct directory ?


Solution

  • If you want your home directory, I recommend using this crate or specifying the absolute path. If you want to save it in any other directories, just use relative or absolute paths, but don't use ~ because Rust doesn't know the context of ~.