Generate unique filename: UUID, Path

Ivy Seo
1 min readFeb 28, 2021

--

A: using UUID

let my_uuid = Uuid::new_v4(); let file_created = File::create(my_uuid.to_string()).expect("create file failed");    println!("uuid: {}", my_uuid); //  buffer write
let mut file_generated = BufWriter::new(file_created);
// write file
file_generated.write_all(format!("{}", m7_data).as_bytes()).expect("write failed");

Filename example: 59199847-dfd9–448a-8af3–3bb41420741e

B: While Loop & Path

// 1) set a path
let path: String = "C:/Users/Desktop/fileName".to_string();
let file_created;
// 2) check if there is file exists
if Path::new(&path).exists() {
// if file already exists, create a new file name to avoid overwerite
let mut num = 1;
let mut new_path: String = "C:/Users/Desktop/fileName".to_string();
// just assign default value for now to initialize


// in C++ : for (num = 1; !(Path::new(&path).exists()); num++)
while Path::new(&new_path).exists() {
num = num + 1;
new_path = format!("{}{}", &path, &num.to_string());
// ex) C:/Users/Desktop/fileName1
}
// 3-a) creates file
file_created = File::create(new_path).expect("create file failed");
} else { // first time the file is generated // 3-b) creates file
file_created = File::create(path).expect("create file failed");
}
letmut file_generated = BufWriter::new(file_created); file_generated.write_all(format!("{}", m7_data).as_bytes()).expect("write failed");

Filename example: fileName1

#Rust

--

--