std::io

std::io Read and Write, including write_all versus partial writes, and read_to_string UTF-8 errors.

主题页正文目前为英文。

std::io is the standard-library I/O module. Read and Write are traits. File, Stdout, TcpStream, and Cursor implement them. Fallible operations return std::io::Result<T>, which is Result<T, std::io::Error>. This is not a third-party async runtime, and it is not serde.

write may transfer fewer bytes than you passed. write_all repeats the write until the whole buffer is sent or an error occurs. read_to_string appends bytes to a String and returns an error if the data is not valid UTF-8; read_to_end is the byte-oriented alternative.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Read::read_to_string, CursorRead all remaining bytes into a String, or fail if the bytes are not valid UTF-8. Use read_to_end when the input may be binary.
Write::write, Write::write_allwrite may transfer fewer bytes than you asked for. write_all keeps writing until the entire buffer is accepted or an error occurs.

read_to_string and UTF-8

read_to_string reads from a type that implements Read and appends to an existing String. On success it returns the number of bytes appended. If the bytes are not valid UTF-8, the call returns Err with ErrorKind::InvalidData and leaves the String unchanged in this example, which starts empty. Cursor wraps an in-memory buffer so the behavior can be shown without touching the filesystem.

Read::read_to_string, Cursor

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

Read all remaining bytes into a String, or fail if the bytes are not valid UTF-8. Use read_to_end when the input may be binary.

ParameterDescription
bufThe destination String. read_to_string appends; it does not clear the string first.

Returns: Ok(byte_count) on success. The byte count is the number of bytes appended, which for valid UTF-8 is also the increase in String::len.

Errors and panics

  • std::io::Error — I/O failures from the reader, or ErrorKind::InvalidData when the bytes are not valid UTF-8. This is a Result, not a panic.
  • The success path uses Cursor<Vec<u8>> in memory. The same methods apply to File, but these examples avoid depending on files on disk.
  • For the two-byte sequence 0xff 0xfe, read_to_string fails with InvalidData and the destination string stays empty.
  • main returns io::Result<()> so that ? can be used. A failure would be reported by the standard Termination implementation.
rust
use std::io::{self, Cursor, Read};

fn main() -> io::Result<()> {
    let mut cursor = Cursor::new(Vec::from(*b"hello"));
    let mut text = String::new();
    let n = cursor.read_to_string(&mut text)?;
    println!("n={n} text={text}");

    let mut bad = Cursor::new(vec![0xff, 0xfe]);
    let mut invalid = String::new();
    let err = bad.read_to_string(&mut invalid).unwrap_err();
    println!("invalid kind={:?} empty={}", err.kind(), invalid.is_empty());
    Ok(())
}

Expected output

n=5 text=hello
invalid kind=InvalidData empty=true

Related: Read::read_to_string, Read::read_to_end

Official documentation →

Partial writes and write_all

Write::write is allowed to write only part of the buffer and still return Ok(n) with n less than buf.len(). Treating a short write as a completed write drops the rest of the data. write_all loops until every byte is written, or until a write returns 0 or an error.

The writer in this example always accepts at most one byte. A single write therefore returns 1 for a three-byte input, while write_all still completes the whole buffer.

Write::write, Write::write_all

fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write_all(&mut self, buf: &[u8]) -> Result<()>
fn flush(&mut self) -> Result<()>

write may transfer fewer bytes than you asked for. write_all keeps writing until the entire buffer is accepted or an error occurs.

ParameterDescription
bufThe bytes to write. write does not promise to consume the whole slice in one call.

Returns: write returns Ok(n) with the number of bytes accepted, which may be less than buf.len() and may be 0. write_all returns Ok(()) only after the whole buffer has been written.

Errors and panics

  • std::io::Error — Returned when the writer fails, or when write_all sees a write of 0 bytes before the buffer is exhausted (ErrorKind::WriteZero).
  • Ignore the Result, or assume that Ok means the whole buffer was written, and you can lose data on a real socket or pipe.
  • flush is part of Write because some destinations buffer output. The example writer flushes as a no-op.
  • Cursor and File also implement Write. Cursor::write_all is used on the previous section to fill an in-memory buffer reliably.
rust
use std::io::{self, Write};

struct OneByteAtATime;

impl Write for OneByteAtATime {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        Ok(1)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn main() -> io::Result<()> {
    let mut writer = OneByteAtATime;
    let n = writer.write(b"abc")?;
    println!("partial write n={n}");
    writer.write_all(b"abc")?;
    println!("write_all ok");
    Ok(())
}

Expected output

partial write n=1
write_all ok

Related: Write::write_all

Official documentation →