Writing a line to a file

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

writeln!(writer, "{}", line)

or in general,

write!(writer, "any format string and the {}", line)
2 Likes

Yes, thanks! How could I have missed that one!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.