Skip to Content
Course content

100: std::fs Functions: read_to_string, write, metadata

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this happen all the time when people first start interacting with the filesystem in Rust. They treat std::fs::write like a logging function—something that just keeps adding data to the end of a file. But that's not how it works.

use std::fs;

fn main() {
    let logs = vec!["User logged in", "Database connection established", "Payment processed"];
    
    for log in logs {
        // I'm trying to save each log entry to a file
        fs::write("app.log", format!("{}\n", log)).expect("Unable to write file");
    }
    
    println!("Logs saved successfully!");
}

The Case of the Disappearing Logs

If you run the code above and then open app.log, you'll notice something frustrating: only the very last entry ("Payment processed") is there. The first two entries have vanished into the void.

The problem is that fs::write is a "convenience" function. It's great for quick tasks, but it has a very specific behavior: it opens the file in write-only mode and truncates it. Truncating is a fancy way of saying "wipe everything currently in this file to zero bytes before writing the new data." Every time the loop iterated, Rust effectively deleted the previous log entry to make room for the new one.

Using the Right Tool for the Job

Now, if your goal is to replace the entire contents of a file (like updating a config.json), fs::write is exactly what you want. It's clean and handles the file opening and closing in one go. But if you need to preserve data, you'd move toward std::fs::OpenOptions. For this lesson, though, let's focus on the three heavy lifters: write, read_to_string, and metadata.

Once you've written a file, you usually need to get that data back. fs::read_to_string is the counterpart to fs::write. It reads the entire file into a String. It's incredibly handy, but it's also dangerous if you don't know how big the file is. If you accidentally try to read_to_string a 10GB log file, your program will likely crash with an "out of memory" error because it's trying to shove the entire file into RAM.

Preventing Crashes with Metadata

This is where std::fs::metadata comes in. Before you commit to reading a file into memory, you should check its properties. metadata returns a Metadata struct that tells you the file size, permissions, and whether the path is actually a file or a directory.

Here is how I would actually handle a "read" operation safely:

use std::fs;

fn main() -> std::io::Result<()> {
    let path = "app.log";
    
    // First, check the metadata
    let meta = fs::metadata(path)?;
    let file_size = meta.len();
    
    println!("File size is {} bytes", file_size);
    
    // Only read the file if it's under 1MB to avoid memory issues
    if file_size < 1_000_000 {
        let content = fs::read_to_string(path)?;
        println!("File content: {}", content);
    } else {
        println!("File is too large to read safely into a string.");
    }
    
    Ok(())
}

I like this approach because it's defensive. In a real production environment, you can't trust that the files on disk are the size you expect. A user might have accidentally piped a massive binary blob into your config file, and checking metadata first saves your app from a catastrophic crash.




📋 Practical Task

Build a File-Based Backup Validator

Your task is to create a small utility that manages a "configuration" file. The program should perform the following logic:

  • Create a file named config.txt and write the string "version=1.0\nstatus=active" to it using std::fs::write.
  • Use std::fs::metadata to verify that the file exists and has a size greater than 0 bytes.
  • If the validation passes, use std::fs::read_to_string to read the content and write that same content into a new file called config.bak.
  • If the metadata check fails (e.g., the file is empty), print an error message and do not create the backup.

Ensure you handle the std::io::Result for all filesystem operations using ? or expect().

Rating
0 0

There are no comments for now.

to be the first to leave a comment.