Checking for file existence with PathBuf to ensure unique filenames

Chris Biscardi
InstructorChris Biscardi

Share this video with your friends

Send Tweet

PathBuf lets us check to see if a file exists before writing to it, so we can take advantage of that to make sure that we don't overwrite a file that already exists, even if the user has indicated a title that would overwrite another file.

let mut i: usize = 0;
loop {
    let dest_filename = format!(
        "{}{}",
        filename,
        if i == 0 {
            "".to_string()
        } else {
            i.to_string()
        }
    );
    let mut dest = garden_path.join(dest_filename);
    dest.set_extension("md");
    if dest.exists() {
        i = i + 1;
    } else {
        fs::rename(garden_tmpfile, &dest)?;
        break;
    }
}