Skip to content

Rust File I/O — Reading and Writing Files with std::fs and std::io

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust File I/O. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust file I/O uses std::fs for file operations, std::io::{Read, Write} for reading/writing, and BufReader/BufWriter for buffered access.

What You'll Learn

  • Reading files
  • Writing files
  • Buffered I/O
  • File metadata and paths

Why It Matters

File I/O is essential for most applications. DodaZIP reads and writes compressed archives using these APIs.

Real-World Use

Log file processing, configuration loading, data export, file format conversion.

use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Write, Read};

fn main() -> io::Result<()> {
    // Write to file
    fs::write("hello.txt", "Hello, World!")?;

    // Read entire file
    let content = fs::read_to_string("hello.txt")?;
    println!("Content: {}", content);

    // Open and read
    let file = File::open("hello.txt")?;
    let reader = BufReader::new(file);
    for line in reader.lines() {
        println!("Line: {}", line?);
    }

    // Append to file
    let mut file = fs::OpenOptions::new()
        .append(true)
        .open("hello.txt")?;
    file.write_all(b"\nAppended line")?;

    // File metadata
    let metadata = fs::metadata("hello.txt")?;
    println!("Size: {} bytes", metadata.len());
    println!("Read only: {}", metadata.permissions().readonly());

    // List directory
    for entry in fs::read_dir(".")? {
        let entry = entry?;
        println!("{}", entry.path().display());
    }

    // Remove file
    fs::remove_file("hello.txt")?;

    Ok(())
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro