turtle
turtle

Reputation: 8103

How to write string to file?

I'm trying to figure out how to write a string to a file. The following gives me the error format argument must be a string literal:

use std::fs::File;
use std::io::{Error, Write};

fn main() -> Result<(), Error> {
    let path = "results.txt";
    let mut output = File::create(path)?;
    let line = println!("{}", "hello");
    write!(output, line);
}

How can I write to a file from a string variable? If I change the follow line it works, but I can't figure out how to write to a file if the string is in a variable.

write!(output, "foo,bar,baz");

Upvotes: 19

Views: 24662

Answers (1)

harmic
harmic

Reputation: 30607

write! is a macro, similar to print!. It expects 2 or more arguments, the first being a writer, the second a format string (which must be a string literal) and after that zero or more expressions which will be placed into the placeholders in the format string.

So, you could combine both your last two lines like this:

fn main() -> std::io::Result<()> {
    let path = "results.txt";
    let mut output = File::create(path)?;
    let line = "hello";
    write!(output, "{}", line)
}

Other methods to write to a Writer include calling std::io::Write::write_all, or to write a slice into a file directly you can use std::fs::write.

Another thing to note: the print! macro does not return the output in a string, it prints the output to stdout. If you want to get the formatted result in a string, use the format! macro:

let my_string = format!("Hello {}", "world");

Upvotes: 24

Related Questions