Hello,
One task that comes up again and again in my work is creating text files from a series of Strings, such that each String becomes a line. And every time I wonder why BufWriter
does not have a method to write a String as a new line?
Basically, I'm doing this:
fn write_line(writer: &mut BufWriter<File>, line: &str) -> Result<(), Error> {
writer.write_all(format!("{}\n", line).as_bytes())?;
Ok(())
}
Is there a better way?
Error
is my crate-primary error type, which has From
implemented for all sorts of errors, including io::Error
. The Strings don't already have a line end included, mostly because BufReader::lines()
creates Strings without line ends. I don't need to flush after each line, in fact, I want to flush less often for better performance, so BufWriter
fits me better than LineWriter
.
Is there a better way, or can we create one?
Thanks!
Best, Oliver