Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a formatted string to a file?

Tags:

rust

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.

like image 646
tez Avatar asked Sep 09 '15 06:09

tez


People also ask

How do you write a file format?

If you are going to write a graphics file format specification, the first thing to do is to make a list of the types of information you are going to store. Then make a second list, of all the auxiliary data a program will need in order to render the data you wrote down in the first list.

What does formatted string mean?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.

Which function we use for write a string into a file?

The fopen() function return a pointer to the FILE stream which is then used with the fputs() function to write the string to the file.


2 Answers

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.)

like image 99
huon Avatar answered Oct 13 '22 22:10

huon


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();
}
like image 5
Alex Avatar answered Oct 13 '22 22:10

Alex