From 2158c712e1d59a807119d3f728164a5d63ce586d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Harabie=C5=84?= Date: Sun, 24 Sep 2017 14:34:23 +0200 Subject: [PATCH] Add cat and ls examples. --- examples/{sample.rs => cat.rs} | 10 +++++---- examples/ls.rs | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) rename examples/{sample.rs => cat.rs} (57%) create mode 100644 examples/ls.rs diff --git a/examples/sample.rs b/examples/cat.rs similarity index 57% rename from examples/sample.rs rename to examples/cat.rs index 3fe230e..7e5faa9 100644 --- a/examples/sample.rs +++ b/examples/cat.rs @@ -1,7 +1,9 @@ extern crate rfat; +use std::env; use std::fs::File; use std::io::BufReader; +use std::io::prelude::*; use std::str; use rfat::FatFileSystem; @@ -11,8 +13,8 @@ fn main() { let buf_rdr = BufReader::new(file); let mut fs = FatFileSystem::new(Box::new(buf_rdr)).unwrap(); let mut root_dir = fs.root_dir(); - let entries = root_dir.list().unwrap(); - for e in entries { - println!("{} - size {} - modified {}", e.get_name(), e.get_size(), e.get_modify_time()); - } + let mut file = root_dir.get_file(&env::args().nth(1).unwrap()).unwrap(); + let mut buf = vec![]; + file.read_to_end(&mut buf).unwrap(); + print!("{}", str::from_utf8(&buf).unwrap()); } diff --git a/examples/ls.rs b/examples/ls.rs new file mode 100644 index 0000000..888eb53 --- /dev/null +++ b/examples/ls.rs @@ -0,0 +1,40 @@ +extern crate rfat; + +use std::env; +use std::fs::File; +use std::io::BufReader; +use std::str; + +use rfat::FatFileSystem; + +fn format_file_size(size: u64) -> String { + const KB: u64 = 1024; + const MB: u64 = 1024*KB; + const GB: u64 = 1024*MB; + if size < 1024 { + format!("{}B", size) + } else if size < MB { + format!("{}KB", size / KB) + } else if size < GB { + format!("{}KB", size / MB) + } else { + format!("{}KB", size / GB) + } +} + +fn main() { + let file = File::open("resources/fat32.img").unwrap(); + let buf_rdr = BufReader::new(file); + let mut fs = FatFileSystem::new(Box::new(buf_rdr)).unwrap(); + let mut root_dir = fs.root_dir(); + let mut dir = match env::args().nth(1) { + None => root_dir, + Some(ref path) if path == "." => root_dir, + Some(ref path) => root_dir.get_dir(&path).unwrap(), + }; + let entries = dir.list().unwrap(); + for e in entries { + let modified = e.modified().format("%Y-%m-%d %H:%M:%S").to_string(); + println!("{:4} {} {}", format_file_size(e.len()), modified, e.file_name()); + } +}