[英]is there a trait to read from stdin or from file in rust?
As a newbie on rust i wonder to know if there is way to use a single function/macro/anything-else to read a line from a passed file or from stdin, passing as argument a kind of buffer reader maybe? 作为关于rust的新手,我想知道是否有办法使用单个函数/ macro / anything-else从传递文件或stdin读取一行,作为参数传递一种缓冲读取器可能?
I haven't found anything that help yet, the following code works fine, once I was able to wrap some validations on a macro I know that code can be improved. 我还没有发现任何有用的东西,下面的代码工作正常,一旦我能够在宏上包装一些验证我知道代码可以改进。 I'm open for suggestion about how to improve that macro indeed 我愿意接受关于如何改进宏观的建议
...
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
}
}
}
....
As shown File and stdin have different treatments, but they both basically do the same thing, run through a loop looking for a valid entry 如图所示,File和stdin有不同的处理方式,但它们基本上都做同样的事情,通过循环查找有效的条目
thanks @PeterHall, that Read trait thing lighted bulb on, I didn't realized that I could pass stdin to BufReader, so that does the trick: 感谢@PeterHall,那个Read trait的东西点亮了灯泡,我没有意识到我可以将stdin传递给BufReader,所以这就是诀窍:
let stdin = io::stdin();
for line in BufReader::new(stdin).lines() {
...
the same way that one does: 与一个人一样:
let f = File::open(file)?;
for line in BufReader::new(f).lines() {
This is what a I was looking for. 这就是我在寻找的东西。
Thanks a mil 谢谢你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.