Rust

Read a File — Whole / Lines / Bytes

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Three common patterns: load it all into memory, iterate line-by-line, or stream bytes. Pick by file size — `read_to_string` is convenient but bad for huge files.
Rust
Raw
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Read};

fn main() -> io::Result<()> {
    // Whole file → String (only OK for small/medium files)
    let contents = fs::read_to_string("Cargo.toml")?;
    println!("len = {}", contents.len());

    // Whole file → Vec<u8> (binary)
    let bytes = fs::read("Cargo.lock")?;
    println!("bytes = {}", bytes.len());

    // Line-by-line — constant memory
    let file = File::open("/etc/hosts")?;
    for line in BufReader::new(file).lines() {
        let line = line?;
        if !line.starts_with('#') { println!("{line}"); }
    }

    // Stream bytes in fixed-size chunks
    let mut f   = File::open("/tmp/big.bin")?;
    let mut buf = [0u8; 4096];
    loop {
        let n = f.read(&mut buf)?;
        if n == 0 { break; }
        // ... process buf[..n] ...
    }
    Ok(())
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.