Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid overwriting data in a txt file with rust

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading