Lesson 4 · Files, storage, I/O, and protection

File Access Methods

A file access method decides how a program reaches the records inside a file: one after another, straight to a numbered position, or through an index by key.

File Access Methods concept diagramThree rows of file records. Sequential: arrows hop from each record to the next. Direct: one arrow jumps from read(4) to record 4. Indexed: one arrow goes from the index entry for key 125 to the block that holds it.Sequentialreset · read_next · write_nextDirect (relative)read(n) · write(n) · position(n)Indexedsearch index · read blockR0R1R2R3R4R5read(4)R0R1R2R3R4index101109118125134
1

Three Ways to Reach a Record

  1. Sequential access – records are processed in order, one after another, from the current position.
  2. Direct (relative) access – any record can be read or written by its record number, in any order.
  3. Indexed access – an index maps keys to record or block addresses, and lookups go through the index.

File access methods define how a process reads and writes the information stored in a file. The operating system sees a file as a sequence of bytes or fixed-size logical records; the access method is the set of operations a program uses to reach them. The three types of file access methods are sequential, direct and indexed.

The choice is not cosmetic. The same lookup can cost one disk read or thousands depending on the method, as the tracer below shows: finding one record takes 7 reads sequentially and 1 read with direct or indexed access.

Do not confuse access methods with file allocation methods. Allocation (contiguous, linked, indexed) is how the OS places a file's blocks on disk. Access is how a program moves through the file's logical records. A linked allocation, for example, makes direct access slow, because reaching block n means following n pointers.

  • One open file can mix methods: jump with position(n), then read_next from there
  • Variable-length records break the simple n × L offset; they need a table of offsets
  • Pipes, sockets and terminals allow sequential access only
  • Where an inode keeps block pointers, direct access is cheap; see inodes
2

Sequential Access

In sequential access the file has a current position pointer. read_next() returns the record at the pointer and advances it; write_next() appends at the pointer and advances it; reset() (rewind) moves the pointer back to the start. Some systems allow skipping forward or backward n records, but never jumping to an arbitrary one.

The model comes from magnetic tape, where the medium physically passes the head in one order. It is still the most common method: compilers read source files this way, logs are appended this way, and streams such as pipes and sockets allow nothing else.

It is ideal when every record is needed anyway, and slow for a lookup: finding one record costs O(n) reads on average, and proving a record is missing costs all of them.

  • Operations: read_next, write_next, reset
  • Model: tape; also every stream, pipe and log
  • Fast for full scans, O(n) for one lookup
  • Cannot jump to an arbitrary record
3

Direct (Relative) Access

The direct access method, also called relative or random access, treats the file as numbered blocks or fixed-length records. read(n) and write(n) operate on record n directly, and position(n) moves the pointer there. Record numbers are relative to the start of the file, so the OS can place the file anywhere on disk.

With fixed-length records of size L, record n starts at byte n × L, so the offset is one multiplication. The disk model is what makes this cheap: a disk head can seek to any block, unlike a tape.

Direct access needs the record number. It is perfect when the position is computable, for example a hash of the key or an airline seat number. It cannot, on its own, find a record by an arbitrary key such as a name.

  • O(1) reads to any record whose number is known
  • Needs fixed-length records, or a table of offsets
  • Relative numbering lets the OS place the file freely
  • Used by databases, hashed files and memory-mapped files
Key reference

Terms, operations, and practical uses

Operations

  • read_next / write_nextSequential: act at the current position, then advance it.
  • reset (rewind)Move the current position back to the start of the file.
  • read(n) / write(n)Direct: act on record n without touching the others.
  • position(n)Direct: move the pointer, then continue sequentially from there.

Index terms

  • Dense indexOne entry per record; works on unsorted files.
  • Sparse indexOne entry per block; needs the records sorted by key.
  • ISAMIndexed sequential access method: a sorted file plus a sparse index.
  • Multi-level indexAn index on the index, the idea behind B+ trees.
Implementation

Finding roll 125 three ways

import os
import struct
import tempfile

RECORD = struct.Struct("<i12s")  # roll number + 12-byte name = 16 bytes
PER_BLOCK = 2  # records per disk block
STUDENTS = [(101, "Asha"), (104, "Ben"), (109, "Chen"), (112, "Dev"), (118, "Eva"),
            (121, "Farid"), (125, "Gita"), (130, "Hugo"), (134, "Ines"), (140, "Jon")]


def unpack(raw):
    roll, name = RECORD.unpack(raw)
    return roll, name.rstrip(b"\0").decode()


def sequential_find(f, roll):
    f.seek(0)  # reset: rewind to the start
    reads = 0
    while raw := f.read(RECORD.size):  # read_next
        reads += 1
        record = unpack(raw)
        if record[0] == roll:
            return record, reads
    return None, reads


def direct_read(f, n):
    # Fixed-size records make the byte offset a multiplication.
    f.seek(n * RECORD.size)
    return unpack(f.read(RECORD.size)), 1


def build_index(f):
    # One entry per block: the first key stored in it.
    index, block = [], 0
    while True:
        f.seek(block * PER_BLOCK * RECORD.size)
        raw = f.read(RECORD.size)
        if not raw:
            return index
        index.append((unpack(raw)[0], block))
        block += 1


def indexed_find(f, index, roll):
    # The index lives in memory; pick the last block whose first key <= roll.
    block = max((b for key, b in index if key <= roll), default=0)
    f.seek(block * PER_BLOCK * RECORD.size)
    data = f.read(PER_BLOCK * RECORD.size)  # one block read
    for i in range(0, len(data), RECORD.size):
        record = unpack(data[i : i + RECORD.size])
        if record[0] == roll:
            return record, block
    return None, block


def show(record):
    return f"{record[0]} {record[1]}" if record else "not found"


with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "students.dat")
    with open(path, "wb") as f:
        for roll, name in STUDENTS:
            f.write(RECORD.pack(roll, name.encode()))

    with open(path, "rb") as f:
        record, reads = sequential_find(f, 125)
        print(f"sequential: {show(record)} after {reads} record reads")

        record, reads = direct_read(f, 6)
        print(f"direct: record 6 at byte {6 * RECORD.size} is {show(record)} after {reads} read")

        index = build_index(f)
        print("index (first key, block):", " ".join(f"{key}:{block}" for key, block in index))
        for roll in (125, 131):
            record, block = indexed_find(f, index, roll)
            print(f"indexed: roll {roll} -> block {block} -> {show(record)} after 1 block read")
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

struct Record {
    int32_t roll;
    char name[12];
};
static_assert(sizeof(Record) == 16, "records must be fixed size");

const int PER_BLOCK = 2;  // records per disk block

string show(const Record* r) { return r ? to_string(r->roll) + " " + r->name : "not found"; }

// Sequential access: rewind, then read_next until the key appears.
pair<Record, int> sequentialFind(fstream& f, int roll) {
    f.clear();
    f.seekg(0);
    Record r{};
    int reads = 0;
    while (f.read(reinterpret_cast<char*>(&r), sizeof r)) {
        reads++;
        if (r.roll == roll) return {r, reads};
    }
    return {Record{}, reads};
}

// Direct access: fixed-size records make the byte offset a multiplication.
Record directRead(fstream& f, int n) {
    f.clear();
    f.seekg(n * sizeof(Record));
    Record r{};
    f.read(reinterpret_cast<char*>(&r), sizeof r);
    return r;
}

// One index entry per block: the first key stored in it.
vector<pair<int, int>> buildIndex(fstream& f, int records) {
    vector<pair<int, int>> index;
    for (int block = 0; block * PER_BLOCK < records; block++) {
        index.push_back({directRead(f, block * PER_BLOCK).roll, block});
    }
    return index;
}

// Indexed access: pick the last block whose first key <= roll, read that block.
int indexedFind(fstream& f, const vector<pair<int, int>>& index, int roll, Record& out) {
    int block = 0;
    for (auto [key, b] : index) {
        if (key <= roll) block = b;
    }
    Record data[PER_BLOCK]{};
    f.clear();
    f.seekg(block * PER_BLOCK * sizeof(Record));
    f.read(reinterpret_cast<char*>(data), sizeof data);  // one block read
    for (int i = 0; i < f.gcount() / (int)sizeof(Record); i++) {
        if (data[i].roll == roll) {
            out = data[i];
            return block;
        }
    }
    out.roll = -1;
    return block;
}

int main() {
    vector<pair<int, string>> students = {{101, "Asha"}, {104, "Ben"},  {109, "Chen"}, {112, "Dev"},
                                          {118, "Eva"},  {121, "Farid"}, {125, "Gita"}, {130, "Hugo"},
                                          {134, "Ines"}, {140, "Jon"}};
    auto path = filesystem::temp_directory_path() / "students.dat";
    {
        ofstream out(path, ios::binary);
        for (auto& [roll, name] : students) {
            Record r{roll, {}};
            strncpy(r.name, name.c_str(), sizeof r.name);
            out.write(reinterpret_cast<char*>(&r), sizeof r);
        }
    }

    fstream f(path, ios::in | ios::binary);
    auto [found, reads] = sequentialFind(f, 125);
    cout << "sequential: " << show(&found) << " after " << reads << " record reads\n";

    Record r = directRead(f, 6);
    cout << "direct: record 6 at byte " << 6 * sizeof(Record) << " is " << show(&r) << " after 1 read\n";

    auto index = buildIndex(f, students.size());
    cout << "index (first key, block):";
    for (auto [key, block] : index) cout << " " << key << ":" << block;
    cout << "\n";
    for (int roll : {125, 131}) {
        Record hit{};
        int block = indexedFind(f, index, roll, hit);
        cout << "indexed: roll " << roll << " -> block " << block << " -> "
             << show(hit.roll == -1 ? nullptr : &hit) << " after 1 block read\n";
    }
    f.close();
    filesystem::remove(path);
}
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Main {
    static final int RECORD = 16; // roll number (4 bytes) + name (12 bytes)
    static final int PER_BLOCK = 2; // records per disk block

    record Student(int roll, String name) {
        public String toString() {
            return roll + " " + name;
        }
    }

    static Student readRecord(RandomAccessFile f) throws IOException {
        int roll = f.readInt();
        byte[] name = new byte[12];
        f.readFully(name);
        return new Student(roll, new String(name, StandardCharsets.US_ASCII).trim());
    }

    // Sequential access: rewind, then read_next until the key appears.
    static int sequentialFind(RandomAccessFile f, int roll, Student[] out) throws IOException {
        f.seek(0);
        int reads = 0;
        while (f.getFilePointer() < f.length()) {
            Student s = readRecord(f);
            reads++;
            if (s.roll() == roll) {
                out[0] = s;
                return reads;
            }
        }
        return reads;
    }

    // Direct access: fixed-size records make the byte offset a multiplication.
    static Student directRead(RandomAccessFile f, int n) throws IOException {
        f.seek((long) n * RECORD);
        return readRecord(f);
    }

    public static void main(String[] args) throws IOException {
        Student[] students = {
            new Student(101, "Asha"), new Student(104, "Ben"), new Student(109, "Chen"), new Student(112, "Dev"),
            new Student(118, "Eva"), new Student(121, "Farid"), new Student(125, "Gita"), new Student(130, "Hugo"),
            new Student(134, "Ines"), new Student(140, "Jon")
        };
        File path = File.createTempFile("students", ".dat");
        try (RandomAccessFile f = new RandomAccessFile(path, "rw")) {
            for (Student s : students) {
                f.writeInt(s.roll());
                byte[] name = new byte[12];
                byte[] raw = s.name().getBytes(StandardCharsets.US_ASCII);
                System.arraycopy(raw, 0, name, 0, raw.length);
                f.write(name);
            }

            Student[] found = new Student[1];
            int reads = sequentialFind(f, 125, found);
            System.out.println("sequential: " + found[0] + " after " + reads + " record reads");

            System.out.println("direct: record 6 at byte " + 6 * RECORD + " is " + directRead(f, 6) + " after 1 read");

            // One index entry per block: the first key stored in it.
            List<int[]> index = new ArrayList<>();
            for (int block = 0; block * PER_BLOCK < students.length; block++) {
                index.add(new int[] {directRead(f, block * PER_BLOCK).roll(), block});
            }
            StringBuilder line = new StringBuilder("index (first key, block):");
            for (int[] e : index) line.append(" ").append(e[0]).append(":").append(e[1]);
            System.out.println(line);

            for (int roll : new int[] {125, 131}) {
                // Indexed access: last block whose first key <= roll, then one block read.
                int block = 0;
                for (int[] e : index) {
                    if (e[0] <= roll) block = e[1];
                }
                f.seek((long) block * PER_BLOCK * RECORD);
                String result = "not found";
                for (int i = 0; i < PER_BLOCK && f.getFilePointer() < f.length(); i++) {
                    Student s = readRecord(f);
                    if (s.roll() == roll) result = s.toString();
                }
                System.out.println("indexed: roll " + roll + " -> block " + block + " -> " + result + " after 1 block read");
            }
        } finally {
            path.delete();
        }
    }
}
Watch it run

Step through it

Running on 10 sorted records, 16 bytes each, 2 per block; target roll 125

block 0101R0104R1block 1109R2112R3block 2118R4121R5block 3125R6130R7block 4134R8140R9students.dat10 records × 16 bytes, 2 per blockreads: 0target: roll 125
Step 1

A file of 10 records in 5 blocks

students.dat holds 10 fixed-size records of 16 bytes, sorted by roll number, two to a disk block. The task: find roll 125, the record R6, using each access method, and count how many reads it costs.

Output
1 / 11
4

Indexed and Indexed Sequential Access

Indexed access adds an index: a separate, much smaller structure of (key, pointer) entries. To find a record, the system searches the index for the key, follows the pointer and reads the block. If the index fits in memory, a lookup by key costs one disk read.

A dense index has one entry per record. A sparse index has one entry per block, holding the block's first key, which works when the records are sorted, because the key must lie in the last block whose first key is not larger.

The indexed sequential access method (ISAM), introduced by IBM, combines both views: the records are kept sorted, so they can still be read sequentially, and a sparse index gives fast lookups by key. When even the index is too large, it is indexed again, giving a multi-level index; a B-tree or B+ tree is the modern, self-balancing form of the same idea.

  • Index = (key, pointer) pairs, searched before the file
  • Dense: one entry per record. Sparse: one per block
  • ISAM = sorted file + sparse index: sequential and keyed access
  • Large files use multi-level indexes, today usually B+ trees
5

Worked Example: Counting Block Reads

An exam question often asks for the number of disk accesses under each method. Work it out block by block.

  • File – 5,000 records of 200 bytes each.
  • Block size – 1 KB (1,024 bytes), so ⌊1024 / 200⌋ = 5 records per block and 1,000 blocks.
  • Target – record number 3,000 (counting from 1).
  • Index – sparse, one 8-byte entry per block: 1,000 entries = 8,000 bytes = 8 blocks, stored on disk.

Sequential. Record 3,000 is in block ⌈3000 / 5⌉ = 600. Reading from the start means reading blocks 1 to 600: 600 block reads.

Direct. Record 3,000 is record index 2,999 counting from 0, so it is in block ⌊2999 / 5⌋ = 599 counting from 0, the 600th block. The system computes this and reads it: 1 block read.

Indexed. Binary search over the 8 index blocks needs at most ⌈log₂ 8⌉ + 1 = 4 block reads to find the right entry, then 1 read for the data block: up to 5 reads. If the index is already cached in memory, as it usually is, it is 1 read.

Direct access wins when the record number is known. Indexed access costs slightly more but works from a key, which is what a real query supplies.

  • Records per block = ⌊block size / record size⌋
  • Sequential cost grows with the record's position
  • Direct: compute the block, read once
  • Indexed: index reads + 1, or just 1 when the index is cached
6

Sequential vs Direct vs Indexed Access

Real systems mix the methods. A database reads a table sequentially for a full scan, directly for a row whose address it knows, and through a B+ tree index for a query by key. The operating system usually provides sequential and direct access, and indexed access is built by the application or a database library on top of direct access.

Sequential vs direct vs indexed access
SequentialDirect (relative)Indexed
Reach record byPosition, in orderRecord numberKey
Cost of one lookupO(n) reads1 readIndex search + 1 read
Extra storageNoneNoneThe index
Record formatAny, even variable lengthUsually fixed lengthAny
Best forFull scans, logs, streamsHashed and computed positionsQueries by key
Device modelTapeDiskDisk
  • Scan everything: sequential
  • Know the position: direct
  • Know only the key: indexed
  • Databases use all three on the same file