Update file

Rust

There are several ways to "update a file".

In one case we open the file for reading read the whole file into memory then separately open the file for writing and write the content.

Another way is to open the file for both reading and writing at the same time, read the content, rewind the file pointer, truncate the file to 0 and then write the new content.

In this example we open the file using the options by setting the 3 flags:

  • read

  • write

  • create

examples/files/update-file/src/main.rs

use std::io::Seek;
use std::io::SeekFrom;
use std::env;
use std::process::exit;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::io::Write;

const SIZE: usize = 10;

fn main() -> Result<(), Box<dyn Error>> {
    let args = env::args().collect::<Vec<String>>();
    if args.len() != 2 {
        eprintln!("Usage: {} TEXT", args[0]);
        exit(1);
    }

    let filename = "message.txt";

    let mut file =  File::options().read(true).write(true).create(true).open(filename)?;

    let mut content = String::new();
    let mut buffer = [0; SIZE];
    loop {
        let size = file.read(&mut buffer)?;
        println!("Read: {size}");
        if size < SIZE {
            break;
        }
        content.push_str(&String::from_utf8(buffer[0..size].to_vec())?);
    }

    println!("old: {content:?}");

    file.seek(SeekFrom::Start(0))?;
    file.set_len(0)?; // truncate

    file.write_all(args[1].as_bytes())?;

    Ok(())

}

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo