1use std::path::PathBuf;
2
3pub fn head(path: &PathBuf, n: u32) -> std::io::Result<()> {
5 let mut line_count: u32 = 0;
6 for _ in read_lines(path)? {
7 line_count += 1;
8 }
9
10 let first_not_to_print: u32 = std::cmp::min(n, line_count);
11
12 let mut at_line: u32 = 0;
13 for line in read_lines(path)? {
14 if at_line >= first_not_to_print {
15 break;
16 }
17 println!("{}", line.expect("failed to read line"));
18 at_line += 1;
19 }
20 Ok(())
21}
22
23pub fn tail(path: &PathBuf, n: u32) -> std::io::Result<()> {
25 let mut line_count: u32 = 0;
26 for _ in read_lines(path)? {
27 line_count += 1;
28 }
29
30 let first_to_print: u32 = line_count.saturating_sub(n);
31
32 let mut at_line: u32 = 0;
33 for line in read_lines(path)? {
34 if at_line >= first_to_print {
35 println!("{}", line.expect("failed to read line"));
36 }
37 at_line += 1;
38 }
39 Ok(())
40}
41
42use std::io::BufRead;
43
44fn read_lines(
45 filename: &PathBuf,
46) -> std::io::Result<std::io::Lines<std::io::BufReader<std::fs::File>>> {
47 let file = std::fs::File::open(filename)?;
48 Ok(std::io::BufReader::new(file).lines())
49}
50
51#[cfg(test)]
52mod tests {
53 #[test]
54 fn test_math() {}
55}