Ensure EOL on files with Rust

This snippet displays how to check a file for a missing newline on the last line. I like this as it demonstrates:

  • Opening files for both reading and writing.
  • Seeking within files.
  • Reading a specific number of bytes from a file.
/// Add a final newline to the end of a file when missing.
///
/// This function is idempotent and will return whether a newline was added or not.
fn ensure_eol(path: &PathBuf) -> std::io::Result<bool> {
    let mut file = OpenOptions::new().read(true).write(true).open(&path)?;
    let mut buffer = [0; 1];

    if file.seek(SeekFrom::End(-1)).is_err() {
        // This typically happens when a file is empty (can't seek to -1 on empty file).
        // Assume this is fine.
        return Ok(false);
    }

    file.read_exact(&mut buffer[..])?; // Reads a single byte as buffer has a capacity of 1
    if buffer == [b'\n'] {
        return Ok(false);
    };

    file.write_all(&[b'\n'])?;
    Ok(true)
}