SHARE
TWEET

Untitled

a guest Feb 23rd, 2019 43 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::fs::File;
  2. use std::io::{BufRead, BufReader};
  3.  
  4. fn main() {
  5.     println!("Hello, world!");
  6.  
  7.     // this is a shorter way of writing your `match` loop. It gives you your
  8.     // `Vec<i64>` on success or panics with an error message if the function
  9.     // fails at opening the file or parsing its contents
  10.     let something = read("temp.txt").unwrap();
  11.  
  12.     println!("{:?}", something);
  13. }
  14.  
  15. // function takes path in the form of string slice and returns enum
  16. // which contains vector of integers on success or an error.
  17. // The use of `dyn std::error::Error` means this function is capable of
  18. // dynamically returning multiple kinds of errors.
  19. fn read(path: &str) -> Result<Vec<i64>, Box<dyn std::error::Error>> {
  20.     println!("Entered Read Function");
  21.     let file = File::open(path)?; // open file by given path
  22.  
  23.     let br = BufReader::new(file);
  24.  
  25.     let mut v = Vec::new();
  26.  
  27.     for line in br.lines() {
  28.         // The `lines()` iterator needs to perform IO to read from the file, and
  29.         // your code has to know what to do if reading from the file ever fails.
  30.         // This code gives you a `&str` representing the contents of the line if
  31.         // reading from the file succeeds, or returns an `io::Error` otherwise.
  32.         let line = line?;
  33.  
  34.         for s in line.split_whitespace() {
  35.             // this parses each `&str` into an `i64` if it succeeds or returns
  36.             // a `ParseIntError` if it fails
  37.             let s = s.parse()?;
  38.  
  39.             // push each `i64` into the `Vec`
  40.             v.push(s);
  41.         }
  42.     }
  43.     Ok(v) // everything is Ok, return vector
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top