]> piware.de Git - learn-rust.git/blobdiff - src/main.rs
File reading and simple error handling
[learn-rust.git] / src / main.rs
index e61306ac95077cf475e0b60fd11d573531a09e2d..973bb2e6c8a3ff790ed25a03f690ea48c6a29084 100644 (file)
@@ -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();
 }