Hey so I’m attempting to make a small program and I want it to have some logs. The issue is that it runs in a for loop and it keeps overwriting the old data written to it. Looking around there might be a fix with ".append()" but I cant seem to find a way to get it working. If I could get some help that would be greatly apricated.
let download_dir = Path::new(download_dir);
fs::create_dir_all(download_dir).unwrap();
fs::rename(&path, download_dir.join(file_name)).unwrap();
let log_dir = "Logs";
fs::create_dir_all(log_dir).unwrap();
let mut file = std::fs::File::create("logs/Logs.txt").expect("create failed").append(true);
file.write_all(format!("{:?}", file_name).as_bytes()).expect("write failed");
file.write_all(format!(" Moved to ").as_bytes()).expect("write failed");
file.write_all(format!("{:?}\n", download_dir.display()).as_bytes()).expect("write failed");
Output
"t3.png" Moved to "Pictures"
Expected
"t1.png" Moved to "Pictures"
"t2.png" Moved to "Pictures"
"t3.png" Moved to "Pictures"
>Solution :
You need to open the file in append mode. You can do this with OpenOptions:
let mut file = std::fs::OpenOptions::new()
.append(true)
.create(true)
.open("logs/Logs.txt")
.expect("create failed");