use std::{error, fs};
use std::fs::File;
use std::io::{ErrorKind, Error, Read};
use std::net::IpAddr;
fn read_username_from_file() -> Result<String, Error> {
let mut f = match File::open("hello.txt") {
Ok(file) => file,
Err(e) => return Err(e)
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e)
}
}
fn read_username_from_file2() -> Result<String, Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
fn read_username_from_file3() -> Result<String, Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
fn read_username_from_file4() -> Result<String, Error> {
fs::read_to_string("hello.txt")
}
fn last_char_of_first_line(text: &str) -> Option<char> {
text.lines().next()?.chars().last()
}
fn main() -> Result<(), Box<dyn error::Error>> {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problems opening the file: {:?}", e)
},
other_error => panic!("Problems opening the file: {:#?}", other_error)
}
};
println!("f: {:#?}", f);
let f = File::open("hello.txt").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Problem creating the file: {:?}", error);
})
} else {
panic!("Problem opening the file: {:?}", error);
}
});
println!("f: {:#?}", f);
let result = read_username_from_file();
println!("result: {:?}", result.unwrap());
let result = read_username_from_file2();
println!("result: {:?}", result.unwrap());
let result = read_username_from_file3();
println!("result: {:?}", result.unwrap());
let result = read_username_from_file4();
println!("result: {:?}", result.unwrap());
last_char_of_first_line("abcde");
let home: IpAddr = "127.0.0.1".parse().unwrap();
println!("home: {}", home);
File::open("hello.txt")?;
Ok(())
}