std::fs::File::create file use relative path which have empty directroy

I use std::fs::File::create with relative path to cteate file,
but when relative path contern a don't exist directory , create will failed .
such as

use std::fs::File;

fn main(){
    let f = File::create("./open/1.txt").unwrap();//will error
   // open is disn't exist
}

why this function can not direct create what I specify the disn‘t exist directory and file
Is it mean I need create it one by one ?

You can use std::fs::create_dir_all to create all the folders that need to be created.

use std::fs::{self, File};
use std::io;

fn main() -> io::Result<()> {
    // Create all folders, if any don't exist.
    fs::create_dir_all("./open/")?;
    // Create the file
    let f = File::create("./open/1.txt")?;
    
    // Success
    Ok(())
}
2 Likes