vasily
vasily

Reputation: 2920

Writing string to a file

pub fn write_file(path: &str, content: &str) -> Result<(), std::io::Error> {
    OpenOptions::new()
        .write(true)
        .create(true)
        .open(path)
        .and_then(|mut file| {
            file.lock_exclusive().and_then(|()| {
                file.write_all(content.as_bytes())
            });
            Ok(())
        })
}

How can I modify this method that it works similarly to fprintf:

write_file("/output.txt", "hello, {}. look {}", name, box);

Upvotes: 2

Views: 863

Answers (1)

user4815162342
user4815162342

Reputation: 154876

You would need to make your function a macro. For example:

macro_rules! write_file {
    ($path: expr, $($content: expr),+) => {{
        OpenOptions::new()
            .write(true)
            .create(true)
            .open($path)
            .and_then(|mut file| {
                file.lock_exclusive().and_then(|()| {
                    write!(file, $($content,)*)
                })
            })
    }}
}

//write_file!("/tmp/foo", "hello {}\n", "world")?;

Playground

If you plan to actually use this, be sure to wrap the File in a BufWriter to avoid multiple tiny writes being sent to the OS:

.and_then(|mut file| {
    file.lock_exclusive()?;
    let mut w = BufWriter::new(file);
    write!(w, $($content,)*)?;
    w.flush()   // flush explicitly so write error can propagate
})

Upvotes: 4

Related Questions