Pagini recente » Cod sursa (job #2735912) | Cod sursa (job #198573) | Cod sursa (job #1726747) | Cod sursa (job #1784871) | Cod sursa (job #2447028)
use std::fs::{self,File};
use std::io::{self, BufReader, Error, BufRead, ErrorKind};
// function takes path in the form of string slice and returns enum
// which contains vector of integers on success or IO error type, see `std::io::Error`
fn read(path: &str) -> Result<Vec<i64>, io::Error> {
let file = File::open(path)?; // open file by given path
// wrap file into generic buffered reader, it will use 4 KB buffer internally
// to reduce number of syscalls, thus improving performance
let br = BufReader::new(file);
// create an empty vector, type of the stored elements will be inferred
let mut v = Vec::new();
// br.lines() creates an iterator over lines in the reader
// see: https://doc.rust-lang.org/std/io/trait.BufRead.html#method.lines
for line in br.lines() {
// IO operations generally can return error, we check if got
// an error,in which case we return this error as the function result
let line = line?;
for number_as_string in line.split_whitespace() {
let n = number_as_string
.parse() // call `str::parse::<i64>(&self)` method on the trimmed line, which parses integer
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?; // parse() can return error (e.g. for string "abc"), here if we got it, we convert it to `std::io::Error` type and return it as function result
v.push(n); // push acquired integer to the vector
}
}
Ok(v) // everything is Ok, return vector
}
//match v {
// Ok(the_vec_of_numbers) => { /* rest of your logic */ },
// Err(err) => { /* handle the io error */ }
//}
fn main() {
let v = read("adunare.in");
let mut fileout = File::create("adunare.out");
match v {
Ok(v) => {
fs::write ("adunare.out",format!("{}",v.iter().sum::< i64 > ()));
},
Err(err) => {
panic ! ("Empty file!");
}
}
}