Skip to content

Struct std::io::Stdin

进程的标准输入流的句柄。

每个句柄都是对该进程输入数据的全局缓冲区的共享引用。可以对句柄进行 lock,以获取对 BufRead 方法 (例如 .lines()) 的完全访问权限。 否则,将针对其他读取锁定对此句柄的读取。

该句柄实现了 Read trait,但请注意,必须谨慎执行 Stdin 的并发读取。

io::stdin 方法创建。

rust
pub struct Stdin { /* private fields */ }

Windows 可移植性注意事项

在控制台中操作时,此流的 Windows 实现不支持非 UTF-8 字节序列。 尝试读取无效的 UTF-8 字节将返回错误。

在具有分离控制台的进程中,例如使用 #![windows_subsystem = "windows"] 的进程,或在从此类进程派生的子进程中,包含的句柄将为空。

在这种情况下,标准库的 Read 和 Write 将什么都不做,默默地成功。 通过标准库或通过原始 Windows API 调用的所有其他 I/O 操作都将失败。

示例

rust
use std::io;

fn main() -> io::Result<()> {
    let mut buffer = String::new();
    let stdin = io::stdin(); // 我们在这里得到 `Stdin`。
    stdin.read_line(&mut buffer)?;
    Ok(())
}

Implementations

impl Stdin

lock

将此句柄锁定到标准输入流,返回可读的保护。

当返回的锁离开作用域时,将释放该锁。 返回的防护还实现了用于访问底层数据的 ReadBufRead traits

rust
pub fn lock(&self) -> StdinLock<'static>

返回值:返回一个 StdinLockstdinLock实现了 Read

rust
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let mut lock = stdin.lock();

    let mut buf = [0u8; 16];
	
    lock.read(&mut buf)?;

    println!("read: {:?}", &buf[..]);
    Ok(())
}

为什么必须有 lock

多线程场景:

  • 只有一个线程持有 StdinLock
  • 多个线程同时读 stdin 会 panic / 未定义行为(被 Rust 防止)
rust
use std::io::{self, Read};
use std::thread;

fn main() {
    let stdin = io::stdin();

    thread::scope(|s| {
        let mut lock = stdin.lock();
        s.spawn(|| {
            let mut buf = [0u8; 8];
            lock.read(&mut buf).unwrap();
        });
    });
}

read_line

锁定此句柄并读取输入行,并将其添加到指定的缓冲区。

有关此方法的详细语义,请参见 BufRead::read_line 上的文档。

rust
pub fn read_line(&self, buf: &mut String) -> Result<usize>

参数

  • buf:被读入的缓冲区,如String

返回值:返回读取的内容所占的字节数

rust
use std::io;

fn main()  {
    let stdin = io::stdin(); // 我们在这里得到 `Stdin`。
	let mut buffer=String::new();
	let line = stdin.read_line(&mut buffer);

	println!("读取的内容:{}",buffer);
	println!("读取的总字节数:{}",line.unwrap());
}

lines

消费这个句柄并在输入行上返回一个迭代器。

有关此方法的详细语义,请参见 BufRead::lines 上的文档。

rust
pub fn lines(self) -> Lines<StdinLock<'static>>

返回值:返回一个Lines迭代器,迭代器中的每一项就是当前行的读取内容

rust
use std::io;

fn main() {
    let stdin = io::stdin(); // 我们在这里得到 `Stdin`。
    let lines = stdin.lines();

    for line in lines {
        println!("{:#?}", line);
    }
}

Trait Implementations

impl AsFd for Stdin

as_fd

借用文件描述符。

rust
fn as_fd(&self) -> BorrowedFd<'_>

impl AsHandle for Stdin

Available on Windows only.

as_handle

借用句柄。

rust
fn as_handle(&self) -> BorrowedHandle<'_>

impl AsRawFd for Stdin

as_raw_fd

提取原始文件描述符。

rust
fn as_raw_fd(&self) -> RawFd

impl AsRawHandle for Stdin

Available on Windows only.

as_raw_handle

提取原始句柄。

rust
 fn as_raw_handle(&self) -> RawHandle

impl Debug for Stdin

fmt

使用给定的格式化程序格式化该值。

rust
fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl IsTerminal for Stdin

is_terminal

如果 descriptor/handle 引用 terminal/tty,则返回 true。

rust
fn is_terminal(&self) -> bool

impl Read for Stdin

read

从该源中提取一些字节到指定的缓冲区中,返回读取的字节数。

rust
fn read(&mut self, buf: &mut [u8]) -> Result<usize>

read_buf

从此源中提取一些字节到指定的缓冲区中。

rust
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()>

read_vectored

与 read 相似,不同之处在于它读入缓冲区的一部分。

rust
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

is_read_vectored

确定此 Read 是否具有有效的 read_vectored 实现。

rust
fn is_read_vectored(&self) -> bool

read_to_end

读取所有字节,直到此源中的 EOF 为止,然后将它们放入 buf。

rust
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>

read_to_string

读取这个源中的所有字节,直到 EOF 为止,然后将它们追加到 buf。

rust
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>

read_exact

读取填充 buf 所需的确切字节数。

rust
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>

read_buf_exact

读取填充 cursor 所需的确切字节数。

rust
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()>

by_ref

为这个 Read 实例创建一个 “by reference” 适配器。

rust
fn by_ref(&mut self) -> &mut Self
where
  Self: Sized,

bytes

将此 Read 实例的字节数转换为 Iterator。

rust
fn bytes(self) -> Bytes<Self> 
where
  Self: Sized,

chain

创建一个适配器,将这个流与另一个链接起来。

rust
fn chain<R: Read>(self, next: R) -> Chain<Self, R> 
where
  Self: Sized,

take

创建一个适配器,最多从中读取 limit 个字节。

rust
fn take(self, limit: u64) -> Take<Self> 
where
  Self: Sized,

Auto Trait Implementations

impl RefUnwindSafe for Stdin

impl Send for Stdin

impl Sync for Stdin

impl Unpin for Stdin

impl UnwindSafe for Stdin

Blanket Implementations

impl<T> Any for T

rust
impl<T> Any for T
where
  T: 'static + ?Sized,

impl<T> Borrow<T> for T

rust
impl<T> Borrow<T> for T
where
  T: ?Sized,

impl<T> BorrowMut<T> for T

rust
impl<T> BorrowMut<T> for T
where
  T: ?Sized,

impl<T> From<T> for T

impl<T, U> Into<U> for T

rust
impl<T, U> Into<U> for T
where
  U: From<T>,

impl<T, U> TryFrom<U> for T

rust
impl<T, U> TryFrom<U> for T
where
  U: Into<T>,

impl<T, U> TryInto<U> for T

rust
impl<T, U> TryInto<U> for T
where
  U: TryFrom<T>,

MIT Licensed