[Avg. reading time: 9 minutes]

File Handling

fs module is not part of the Rust prelude You must explicitly import it using

use std::fs

Rust Prelude

  • Prelude = things Rust imports automatically
  • Kept intentionally small
  • Focuses on commonly used traits and types
  • File handling is not included, so you import it manually

The Data file should be in the same level src folder.

data.txt should be at the same level src folder

Read Entire File

    let contents = fs::read_to_string("data.txt").unwrap();
  • Reads full file into a String
  • Assumes file is UTF-8 encoded
  • unwrap() will crash if file is missing or invalid

Read Entire File but processes it Line by Line

    let contents = fs::read_to_string("data.txt").unwrap();
    for line in contents.lines(){
        println!("{}",line);
    }

  • Still loads the entire file into memory first
  • .lines() gives an iterator over each line
  • Cleaner for processing structured text
  • Good for small to medium files

Buffer Read (large files)

    let file = File::open("data.txt").unwrap();
    let reader = BufReader::new(file);

    for _line in reader.lines() {
        // simulate processing
    }
  • Reads file incrementally (streaming)
  • Avoids loading entire file into memory
  • Suitable for large files and data pipelines

Read non UTF-8 or Binary files

let contents = fs::read("data.txt").unwrap();
  • Returns Vec (raw bytes)
  • Does not assume encoding
  • Works for:
    • Images (PNG, JPEG)
    • Parquet, Avro, ORC
    • Compressed files (ZIP, GZIP)
    • Non-UTF-8 text files

Read large Binary file

Combine Buffer and read :)

let file = File::open("big_file.parquet").unwrap();
    let mut reader = BufReader::new(file);

    let mut buffer = [0u8; 8192];

    loop {
        let n = reader.read(&mut buffer).unwrap();
        if n == 0 {
            break;
        }

Read Metadata about file

let meta = fs::metadata("data.txt").unwrap();
println!("Size: {} bytes", meta.len());
println!("Is file: {}", meta.is_file());
println!("Is dir: {}", meta.is_dir());

Summary

  • Small text files > read_to_string()
  • Large text files > BufReader
  • Binary / unknown encoding > read()
git clone https://github.com/gchandra10/rust_readfile_demo

Write File


    let mut text = String::new();
    text.push_str("Rust is strong and statically typed language.");
    text.push_str("Rust is super strict.");
    fs::write("newfile.txt",text);

Points to remember

  • Simple to use
  • Will replace the contents of an existing file
  • Writes entire contents of the file.

Append to File

#![allow(unused)]
fn main() {
    let mut text = String::new();
    let mut file = fs::OpenOptions::new()
        .append(true)
        .open("newfile.txt")
        .unwrap();
        
    file.write(b"Rust is awesome");
}

}

Write fn doesn’t care about datatype. It thinks data is a series of bytes and it expects the value to be an array of u8 values.

git clone https://github.com/gchandra10/rust_writefile_demo.git

Simple Find Command Line simulator

git clone https://github.com/gchandra10/rust_find_demo.git
cargo run --bin simple_find friends.txt Ross

cargo run --bin word_find friends2.txt Your

cargo run --bin word_find friends2.txt Your -i

Good resource if you want to recreate standard Linux commands using RUST

https://doc.rust-lang.org/rust-by-example/std_misc/fs.html

#file #read #writeVer 2.0.22

Last change: 2026-04-01