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.
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.
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.
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.
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.)
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With