Expand description

This crate allows you to specify an offset for reads and writes, without changing the current position in a file. This is similar to pread() and pwrite() in C.

The major advantages of this type of I/O are:

  • You don’t need to seek before doing a random-access read or write, which is convenient.
  • Reads don’t modify the file at all, so don’t require mutability.


Read the fifth 512-byte sector of a file:

use std::fs::File;
use positioned_io2::ReadAt;

// note that file does not need to be mut
let file = File::open("tests/pi.txt")?;

// read up to 512 bytes
let mut buf = [0; 512];
let bytes_read = file.read_at(2048, &mut buf)?;

Note: If possible use the RandomAccessFile wrapper. ReadAt directly on File is very slow on Windows.

Write an integer to the middle of a file:

use std::fs::OpenOptions;
use positioned_io2::WriteAt;
use byteorder::{ByteOrder, LittleEndian};

// put the integer in a buffer
let mut buf = [0; 4];
LittleEndian::write_u32(&mut buf, 1234);

// write it to the file
let mut file = OpenOptions::new().write(true).open("foo.data")?;
file.write_all_at(1 << 20, &buf)?;

Or, more simply:

use std::fs::OpenOptions;
use byteorder::LittleEndian;
use positioned_io2::WriteBytesAtExt;

let mut file = OpenOptions::new().write(true).open("foo.data")?;
file.write_u32_at::<LittleEndian>(1 << 20, 1234)?;

Read from anything else that supports ReadAt, like a byte array:

use byteorder::BigEndian;
use positioned_io2::ReadBytesAtExt;

let buf = [0, 5, 254, 212, 0, 3];
let n = buf.as_ref().read_i16_at::<BigEndian>(2)?;
assert_eq!(n, -300);


Read or write with a given inherent byte-order.

Adapts a ReadAt or WriteAt into a Read or Write.

A wrapper for File that provides optimized random access through ReadAt and WriteAt.

Adapts a ReadAt or WriteAt into a Read or Write, with better seeking.

A window into another ReadAt or WriteAt.


Trait for reading bytes at an offset.

Extends ReadAt with methods for reading numbers at offsets.

Trait to get the size in bytes of an I/O object.

Trait for writing bytes at an offset.

Extends WriteAt with methods for writing numbers at offsets.