作为 rust 的新手,我想知道是否有办法使用单个函数/宏/其他任何东西从传递的文件或 stdin 中读取一行,作为参数传递一种缓冲区阅读器?
我还没有找到任何有帮助的东西,下面的代码工作正常,一旦我能够在宏上包装一些验证,我知道代码可以改进。我愿意就如何改进该宏提出建议
...
macro_rules! validate {
($line:expr, $blank:expr, $squeeze:expr, $line_count:expr, $show_number:expr) => {
if $line.len() <= 0 {
$blank +=1;
} else{
$blank = 0;
}
if $squeeze & ($blank > 1) {
continue;
}
if $show_number {
$line_count += 1;
}
}
}
...
for file in opt.files {
blank_line_count = 0;
line_count = 0;
if file.to_str() != Some("-") {
let f = File::open(file)?;
for line in BufReader::new(f).lines() {
let l = line.unwrap();
validate!(l, blank_line_count, opt.squeeze_blank, line_count, opt.number); // will continue the loop if not valid
println!("{}", format_line(l, opt.show_ends, opt.show_tabs, opt.show_nonprinting, line_count)); // will be skipped if not valid
}
} else {
let stdin = io::stdin();
let mut bytes_read: usize;
loop {
let mut line = String::new();
bytes_read = stdin.lock().read_line(&mut line).expect("Could not read line");
if bytes_read == 0 { break; }
line.pop();
validate!(line, blank_line_count, opt.squeeze_blank, line_count, opt.number);// will continue the loop if not valid
println!("{}", format_line(line, opt.show_ends, opt.show_tabs, opt.show_nonprinting, line_count)); // will be skipped if not valid
}
}
}
....
如图所示,File和stdin有不同的处理方式,但它们基本上都做同样的事情,通过循环运行以查找有效的条目
谢谢@PeterHall,那个 Read trait 的东西点亮了灯泡,我没有意识到我可以将 stdin 传递给 BufReader,所以这就是诀窍:
let stdin = io::stdin();
for line in BufReader::new(stdin).lines() {
...
与一个人一样:
let f = File::open(file)?;
for line in BufReader::new(f).lines() {
这就是我一直在寻找的。
谢谢一密尔