// Created on savesnippets.com ยท https://savesnippets.com/jmI4UPmSQQwfZn 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 (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(()) }