From 56e1367f9394b43c2c8f1e4119df70f02d57ba75 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Mon, 23 Aug 2021 13:52:54 +0200 Subject: [PATCH] File reading and simple error handling --- src/main.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/main.rs b/src/main.rs index e61306a..973bb2e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,8 @@ mod word_utils; use std::collections::HashMap; +use std::io::{prelude::*, ErrorKind}; +use std::fs::File; use word_utils::{first_word, second_word}; @@ -67,8 +69,37 @@ fn test_hashmaps() { println!("collect_scores after rebuilding with doubling: {:?}", collect_scores); } +fn test_files() { + if let Ok(mut f) = File::open("Cargo.toml") { + let mut contents = String::new(); + match f.read_to_string(&mut contents) { + Ok(len) => println!("successfully opened Cargo.toml: {:?}, contents {} bytes:\n{}\n----------", f, len, contents), + Err(e) => panic!("could not read file: {:?}", e) + } + } else { + println!("could not open Cargo.toml"); + } + + // alternative form, more specific error checking + let mut f = File::open("Cargo.toml").unwrap_or_else(|e| { + if e.kind() == ErrorKind::NotFound { + println!("Cargo.toml not found, falling back to /dev/null"); + // need to return a File + File::open("/dev/null").unwrap() + } else { + panic!("Could not open Cargo.toml: {:?}", e); + } + }); + let mut contents = String::new(); + let len = f.read_to_string(&mut contents).unwrap_or_else(|e| { + panic!("Could not read file: {:?}", e); + }); + println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents); +} + fn main() { test_strings(); test_vectors(); test_hashmaps(); + test_files(); } -- 2.39.5