Reputation: 65
I'm having trouble writing a few strings into my .txt file without them overwriting each other
This is an example:
for i in 1..100{
fs::write("*PATH*", i.to_string()).expect("Unable to write file");
}
I'm thinking it should write every singe one right after each other but it doesn't! It overwrites and when I open the document it's just the last written number.
I couldn't find anything on the web since this way of writing into files seems to be rather new.
Upvotes: 3
Views: 3578
Reputation: 35560
I couldn't find anything on the web since this way of writing into files seems to be rather new.
It's not rather new, it's rather wrong (for this use case). Open the file beforehand and write to that so it appends, instead of calling fs::write
every single loop, which will reopen and close the file every iteration, which is not only slow, but causes your file to get overwritten:
use std::fs::OpenOptions;
use std::io::prelude::*;
let file = OpenOptions::new()
.write(true)
.open("/path/to/file")
.expect("Could not open file");
for i in 1..100 {
file.write_all(i.to_string().as_bytes()).expect("Unable to write to file");
}
Upvotes: 1
Reputation: 26245
You can open the File
before entering the loop. You can further simplify writing to the file, by using the write!
and writeln!
macros. Which allows you to utilize Rust's formatting functionality avoiding the need to explicitly do i.to_string()
.
Since you're performing a lot of (small) writes, then consider also wrapping it in a BufWriter
to minimize the amount of total system calls performed.
use std::fs::File;
use std::io::{BufWriter, Write};
fn main() {
let path = "...";
let f = File::create(path).expect("unable to create file");
let mut f = BufWriter::new(f);
for i in 1..100 {
write!(f, "{}", i).expect("unable to write");
}
}
If the file already exists, and you want to continuously append to it every time you execute your program. Then you can open it using OpenOptions
and specifically enabling append mode by using append(true)
:
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
fn main() {
let path = "...";
let f = OpenOptions::new()
.write(true)
.append(true)
.open(path)
.expect("unable to open file");
let mut f = BufWriter::new(f);
for i in 1..100 {
write!(f, "{}", i).expect("unable to write");
}
}
Upvotes: 5