【问题标题】:Read lines from std input using Rust使用 Rust 从标准输入中读取行
【发布时间】:2021-03-10 20:37:35
【问题描述】:

您好,我希望能够将包含 json 行的文件读取到这样的 rust 应用程序中

$ cargo run < users.json

然后将这些行作为迭代器读取。到目前为止,我有这段代码,但我不希望文件被硬编码,而是像上面一行一样通过管道传输到进程中。

use std::fs::File;
use std::io::{self, prelude::*, BufReader};


fn main() -> io::Result<()> {
    let file = File::open("users.json")?;
    let reader = BufReader::new(file);

    for line in reader.lines() {
       
       println!("{}", line);
    }

    Ok(())
}

我刚刚解决了这个问题

use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        println!("{}", line.unwrap());
    }
}

【问题讨论】:

  • 如果你像 myapp &lt; users.json 这样称呼你的应用程序,那么这个管道基本上是由操作系统制作的,文件的内容将在你的应用程序的标准输入中,只需从控制台读取它。
  • 但是在cargo run 的情况下,我不确定货物转发文件内容到您的应用程序中。你可以尝试阅读std::io::stdin,也许你会明白

标签: rust


【解决方案1】:

cargo help run 透露:

NAME
       cargo-run - Run the current package

SYNOPSIS
       cargo run [options] [-- args]

DESCRIPTION
       Run a binary or example of the local package.

       All the arguments following the two dashes (--) are passed to the binary to run. If you're passing arguments to both Cargo and the binary, the ones after -- go to the binary, the ones before go to Cargo.

所以传递参数的语法是:

cargo run -- foo bar baz

然后您可以像这样访问这些值:

let args: Vec<String> = env::args().collect();

一个完整的最小示例是:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    dbg!(&args);
}

运行 cargo run -- users.json 会导致:

$ cargo run -- users.json                                                                                                                                                                                                                       
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/sandbox users.json`
[src/main.rs:5] &args = [
    "target/debug/sandbox",
    "users.json",
]

【讨论】:

  • 我尝试过没有成功 $ cargo run
  • @Ro.我为你添加了一个例子:-)
【解决方案2】:
use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        println!("{}", line.unwrap());
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 2013-03-30
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多