Skip to content

Commit

Permalink
fix: cat command
Browse files Browse the repository at this point in the history
  • Loading branch information
zztkm committed Jun 2, 2024
1 parent 87642c0 commit e81f79d
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// #86442 <https://github.com/rust-lang/rust/issues/86442>
#![feature(io_error_more)]

use clap::{Parser, Subcommand};
use std::io::{Read, Write};

Expand All @@ -24,14 +27,21 @@ fn main() {

// files を入力順に stdout に出力する
// 最後のファイルは改行をしない
let mut iter = files.iter().peekable();
while let Some(file) = iter.next() {
let content = std::fs::read_to_string(file).unwrap();
if iter.peek().is_none() {
write!(&mut stdout, "{}", content).unwrap();
} else {
writeln!(&mut stdout, "{}", content).unwrap();
}
for file in files {
let content = match get_file_data(file) {
Ok(content) => content,
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => {
format!("ztb cat: {}: No such file or directory\n", file)
}
std::io::ErrorKind::IsADirectory => {
format!("ztb cat: {}: Is a directory\n", file)
}
_ => format!("ztb cat: {}: {}", file, e),
},
};

write!(&mut stdout, "{}", content).unwrap();
}
} else {
// files の指定がない場合は標準入力から読み取る
Expand All @@ -48,3 +58,8 @@ fn main() {
}
}
}

/// 与えたら path のファイル内容を返します。
fn get_file_data(path: &str) -> std::io::Result<String> {
std::fs::read_to_string(path)
}

0 comments on commit e81f79d

Please sign in to comment.