Update locked file

Rust

examples/update-locked-file/Cargo.toml

[package]
name = "update-locked-file"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
file-lock = "2.1.11"

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

extern crate file_lock;

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

use file_lock::{FileLock, FileOptions};


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 buffer = [0; 1000];
    let is_blocking = true;
    let options = FileOptions::new().read(true).write(true).create(true);

    let mut filelock = FileLock::lock(&filename, is_blocking, options)?;
    let res = filelock.file.read(&mut buffer)?;

    let content = String::from_utf8(buffer[0..res].to_vec())?;
    println!("old: {content:?}");

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

    filelock.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