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(())
}
Create a free account and build your private vault. Share publicly whenever you want.