Hi, Michael,
In lesson 5, the section on std::fs::File, you leave appending to a file as a bonus exercise. Here's my solution
extern crate gtk;
use gtk::prelude::*;
use std::fs::{File, OpenOptions};
use gtk::{Button, Window, WindowType};
use std::io::{Write, ErrorKind};
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = Window::new(WindowType::Toplevel);
window.set_title("First GTK+ Program");
window.set_default_size(350, 70);
let button = Button::new_with_label("Click me!");
window.add(&button);
window.show_all();
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
button.connect_clicked(|_| {
write_me(b"I was clicked.\n")
.expect("Problem writing to file.");
});
gtk::main();
}
fn write_me(line: &[u8; 15]) -> std::io::Result<()> {
let mut file = OpenOptions::new()
.append(true)
.open("mylog.txt")
.unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("mylog.txt").unwrap_or_else(|error| {
panic!("Problem creating file: {:?}", error);
})
} else {
panic!("Can't open file: {:?}", error);
}
});
file.write(line)
.expect("Error writing to file!");
Ok(())
}
Cheers,
Mitch