Fork me on GitHub

Project Notes

#348 Rust File Handling

Reviewing common file operations with rust

Notes

Create

Create a file with std::fs::File::create

  • Opens a file in write-only mode.
  • Create a file if it does not exist, truncates it if it does.
  • Alternatives:
    • create_buffered Opens a file in write-only mode with buffering
    • create_new Creates a new file in read-write mode; error if the file exists.

Example:

use std::fs::File
let mut file = File::create("name.txt").expect("failed");

Or using the ? operator:

let mut file = File::create("name.txt")?;

Write

Write to a file with write_all

  • Attempts to write an entire buffer into this writer.

Example:

use std::io::Write;
file.write_all("Hello".as_bytes()).expect("failed");
// or
file.write_all("Hello".as_bytes())?;

Open for Append

Open a file for append using OpenOptions

  • A builder used to configure how a File is opened and what operations are permitted on the open file.
  • The File::open and File::create methods are aliases for commonly used options using this builder.

Example:

use std::fs::OpenOptions;
let mut file = OpenOptions::new().append(true).open("name.txt").expect("failed");
file.write_all(" world!\n".as_bytes()).expect("failed");
// or
let mut file = OpenOptions::new().append(true).open("name.txt")?;
file.write_all(" world!\n".as_bytes())?;

Read File

Read from a file with read_to_string

Example:

use std::io::Read;
let mut file = std::fs::File::open("name.txt").unwrap();
file.read_to_string(&mut contents).unwrap();
// or
let mut file = std::fs::File::open("name.txt")?;
file.read_to_string(&mut contents)?;

Delete File

Delete a file with remove_file

use std::fs;
fs::remove_file("name.txt").expect("failed");
// or
fs::remove_file("name.txt")?;

Example Code

See file-demo/src/main.rs.

use std::fs;
use std::io::{Write, Read};

fn create_file(filename: &str, content: &str) -> std::io::Result<()> {
    println!("# creating file: {}", filename);
    let mut file = fs::File::create(filename)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

fn append_to_file(filename: &str, content: &str) -> std::io::Result<()> {
    println!("# appending to file: {}", filename);
    let mut file = fs::OpenOptions::new().append(true).open(filename)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}

fn read_file(filename: &str) -> std::io::Result<String> {
    println!("# reading from file: {}", filename);
    let mut file = fs::File::open(filename)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn delete_file(filename: &str) -> std::io::Result<()> {
    println!("# deleting file: {}", filename);
    fs::remove_file(filename)?;
    Ok(())
}

fn main() -> std::io::Result<()> {
    let filename = "example.txt";

    create_file(&filename, "Hello World!\n")?;
    println!("{}", read_file(&filename)?);
    append_to_file(&filename, "Appended content to the file.\n")?;
    println!("{}", read_file(&filename)?);
    delete_file(&filename)?;

    Ok(())
}

Run:

$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
    Running `target/debug/file-demo`
# creating file: example.txt
# reading from file: example.txt
Hello World!

# appending to file: example.txt
# reading from file: example.txt
Hello World!
Appended content to the file.

# deleting file: example.txt

Credits and References

About LCK#348 rust

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

Project Source on GitHub Return to the LittleCodingKata Catalog
About LittleCodingKata

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.

Follow the Blog follow projects and notes as they are published in your favourite feed reader