Ch11.7: Random Access I/O

Seek Operations

fast_io provides seek operations in the ::fast_io::operations namespace to move the file position. The operation you use depends on the direction of the file:

There are also _rewind variants to seek back to the beginning, and _seek_bytes variants that take a byte offset directly.


#include <fast_io.h>
#include <fast_io_device.h>

int main()
{
    using namespace ::fast_io::iomnp;
    ::fast_io::obuf_file obf(u8"seekable.txt", ::fast_io::open_mode::out);

    // Write some data
    println(obf, "Hello, World!");

    // Seek back to the beginning (output_stream_rewind)
    ::fast_io::operations::output_stream_rewind(obf);

    // Or seek to a specific offset
    ::fast_io::operations::output_stream_seek(obf, 0);
}
      

Positional I/O (pwrite/pread)

Positional I/O lets you read from or write to a specific offset in a file without changing the file's current position. This is the equivalent of POSIX pread(2) and pwrite(2).

In fast_io, use the operations namespace:

The file position remains unchanged after the call.

Using pwrite for Random Writes


#include <fast_io.h>
#include <fast_io_device.h>

int main()
{
    using namespace ::fast_io::iomnp;
    ::fast_io::obuf_file obf(u8"positional_write.txt", ::fast_io::open_mode::out);

    // Write at specific offsets without disturbing file position
    ::fast_io::operations::pwrite_all(obf, "AAAA", 0uz);
    ::fast_io::operations::pwrite_all(obf, "BBBB", 100uz);
    ::fast_io::operations::pwrite_all(obf, "CCCC", 200uz);
}
      

After this program runs, the file contains "AAAA" at offset 0, "BBBB" at offset 100, and "CCCC" at offset 200. The file position is unaffected by the pwrite calls.

Using pread for Random Reads


#include <fast_io.h>
#include <fast_io_device.h>

int main()
{
    using namespace ::fast_io::iomnp;
    ::fast_io::ibuf_file ibf(u8"positional_write.txt", ::fast_io::open_mode::in);

    char buf1[5]{};
    char buf2[5]{};

    // Read from specific offsets
    ::fast_io::operations::pread_all(ibf, ::fast_io::as_bytes(::fast_io::span{buf1, 4uz}), 0uz);
    ::fast_io::operations::pread_all(ibf, ::fast_io::as_bytes(::fast_io::span{buf2, 4uz}), 100uz);

    println("At offset 0:   ", ::fast_io::mnp::os_c_str(buf1));
    println("At offset 100: ", ::fast_io::mnp::os_c_str(buf2));
}
      

Thread Safety

If multiple threads need to write to the same file concurrently, use a lockable file type like ::fast_io::obuf_file_lockable. Lock it, get the unlocked handle, then use that for better performance. See Ch11.6.

Key Takeaways