How do I write a formatted string to a file?

12,403

Solution 1

The documentation indicates the issue: the write_fmt method takes one argument, of type std::fmt::Arguments, which can be constructed via the format_args! macro. It also suggests the best way to use it:

The write! macro should be favored to invoke this method instead.

One calls write! (or writeln!) just like println!, but by passing the location to write to as the first argument:

write!(&mut writer, "Factorial of {} = {}", num, factorial);

(Note that the docs have a search bar at the top of each page, so one can find documentation on, for example, macros by searching for <name>! there.)

Solution 2

use std::fs::File;
use std::io::Write;

fn main() {
    let mut w = File::create("/tmp/test.txt").unwrap();
    writeln!(&mut w, "test").unwrap();
    writeln!(&mut w, "formatted {}", "arguments").unwrap();
}
Share:
12,403
tez
Author by

tez

Updated on June 26, 2022

Comments

  • tez
    tez almost 2 years

    I want to write output of my function to a file. I expected that write_fmt is what I require:

    use std::{
        fs::File,
        io::{BufWriter, Write},
    };
    
    fn main() {
        let write_file = File::create("/tmp/output").unwrap();
        let mut writer = BufWriter::new(&write_file);
    
        // From my function
        let num = 1;
        let factorial = 1;
    
        writer.write_fmt("Factorial of {} = {}", num, factorial);
    }
    

    Error

    error[E0061]: this function takes 1 parameter but 3 parameters were supplied
      --> src/main.rs:11:12
       |
    11 |     writer.write_fmt("Factorial of {} = {}", num, factorial);
       |            ^^^^^^^^^ expected 1 parameter
    

    This seems wrong and there isn't much available in the documentation.