gpt4 book ai didi

rust - 是否有从 stdin 或 rust 文件中读取的特征?

转载 作者:行者123 更新时间:2023-11-29 08:31:28 25 4
gpt4 key购买 nike

作为 Rust 的新手,我想知道是否有办法使用单个函数/宏/其他任何东西从传递的文件或标准输入中读取一行,作为参数传递一种缓冲区读取器?

我还没有找到任何有用的东西,下面的代码工作正常,一旦我能够在宏上包装一些验证,我就知道代码可以改进。我愿意就如何改进该宏提出建议

...

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() {

这就是我一直在寻找的东西。

万分感谢

关于rust - 是否有从 stdin 或 rust 文件中读取的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com