use std::fs::File;
use std::io::{self, ErrorKind, Read};
fn open_file(file_path: &str) -> File {
let open_file_result = File::open(file_path);
match open_file_result {
Ok(file) => file,
Err(e) => match e.kind() {
ErrorKind::NotFound => match File::create(file_path) {
Ok(fc) => fc,
Err(error_create) => panic!("create file error: {:?}", error_create),
},
other_error => {
panic!("Open file error: {:?}", other_error);
}
},
}
}
fn open_file_unwrap(file_path: &str) -> File {
let file = File::open(file_path).expect("file not exist.");
println!("file: {:?}", file);
return file;
}
fn read_file_from_name(file_path: &str) -> Result<String, io::Error> {
let open_file_result = File::open(file_path);
let mut file = match open_file_result {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut content = String::new();
match file.read_to_string(&mut content) {
Ok(_) => Ok(content),
Err(e) => return Err(e),
}
}
fn read_file_from_name_short(file_path: &str) -> Result<String, io::Error> {
let mut content = String::new();
File::open(file_path)?.read_to_string(&mut content)?;
return Ok(content);
}
pub fn result_recover_study() {
let file_path = String::from("hello.txt");
open_file(&file_path);
open_file_unwrap(&file_path);
let file_content = read_file_from_name(&file_path).expect("read file error.");
println!("file content: {}", file_content);
let file_content2 = read_file_from_name_short(&file_path).expect("read file short error.");
println!("file content2: {}", file_content2);
}