How would I save this to a file instead of stdout?

Viewed 42

I'm probably just missing something simple and I have used std::fs::File

use std::io::{stdout, Write};
use curl::easy::Easy;

fn main() {
    let mut easy = Easy::new();
    easy.url("checkip.amazonaws.com").unwrap();
    easy.write_function(|data| {
        Ok(stdout().write(data).unwrap())
    }).unwrap();
    easy.perform().unwrap();
}
1 Answers

Move a file into the closure and write all the content:

use std::fs::File;
use std::io::{Write};
use curl::easy::Easy;


fn main() {
    let mut file = File::create("foo.txt").expect("open file");
    let mut easy = Easy::new();
    easy.url("checkip.amazonaws.com").unwrap();
    easy.write_function(move |data| {
        file.write_all(data).expect("write data");
        Ok(data.len())
    }).unwrap();
    easy.perform().unwrap();
}
Related