Binary and Random-Access Files

Many programs read a file from its first byte to its last. A file of thousands of same-sized records, such as an inventory table, an index or a disk image, is usually queried one record at a time, and reading 7,000 records to reach record 7,001 wastes time. C's standard I/O functions let you treat such a file as an array of bytes. You store records in binary form, compute where any record starts, jump there with fseek, and read or overwrite only that record.

Binary files and fixed-length records

A binary file holds bytes exactly as the program wrote them, with no conversion to readable characters. Writing a structure with fwrite(&rec, sizeof rec, 1, fp) copies its sizeof rec bytes straight from memory, so every record has the same length whatever values it contains. Unpadded text behaves differently: the number 7 takes one character and 70000 takes five. Fixed-width text records are possible if every field is padded to a set width, and binary mode alone does not make records the same size. The fixed length comes from writing the same-sized structure every time.


A file of raw structures is only readable by programs that share the same structure layout and data representation, such as type sizes and byte order, so treat it as private to compatible builds of the program.


Open such files in binary mode by adding b to the mode string: "rb", "wb" or "r+b". On POSIX systems the flag changes nothing. On Windows a text-mode stream converts line endings and treats byte 0x1A as end of file, which silently corrupts binary data, so always include it.


Because every record has the same size ss, the record with index kk, counting from 0, begins at a byte offset you can compute directly, and the file size tells you how many records exist:


offset(k)=k×sNrecords=file sizes\text{offset}(k) = k \times s \qquad N_{\text{records}} = \frac{\text{file size}}{s}


Take ss from sizeof, never by adding up member sizes by hand: the compiler may insert padding, and those bytes are written to the file too.



Seeking to any byte

Random access means reading or writing at any chosen byte offset without processing the bytes before it. Every open stream keeps a file position indicator, and fread and fwrite advance it by the number of bytes they transfer. Two functions control it:

  • fseek(fp, offset, whence) moves the position and returns 0 on success.
  • ftell(fp) returns the current position as a long count of bytes from the start.

The whence argument decides what offset is measured from:


whence

New position

Typical use with record size ss

SEEK_SET

offset

Jump to record kk: offset ksks

SEEK_CUR

current position + offset

Step back one record: offset −s-s

SEEK_END

file size + offset

Reach the last record: offset −s-s


A row of five 64-byte records labelled record 0 to record 4, with byte offsets 0 to 320 below them and an arrow from an fseek call pointing at record 3.


Example: With 64-byte records, reading record 3 from offset 192 leaves the position at 256. Calling fseek(fp, -64L, SEEK_CUR) returns it to 192, ready to overwrite record 3.


To count records, seek to the end and ask where you are: fseek(fp, 0L, SEEK_END) followed by ftell(fp) / sizeof rec. POSIX guarantees this works; the C standard on its own does not require SEEK_END to be meaningful for binary streams.

Updating a record in place

To overwrite one record and keep the rest, open the file with "r+b", which allows reading and writing without truncating. Two other modes look tempting but fail: "w+b" empties the file when it opens, and "a+b" sends every write to the end of the file regardless of any fseek.


On an update stream, a read must not be followed directly by a write without an intervening positioning call such as fseek, fsetpos or rewind, unless the read reached end of file; after a write, a following read needs fflush or a positioning call. For record updates fseek is the natural choice, so the usual sequence is: seek to record kk, call fread and check that it returned 1, change the copy in memory, seek back by ss bytes, then call fwrite.



What to remember

  • Binary mode stores bytes unchanged; writing the same-sized structure each time puts records at fixed offsets.
  • Record kk, counted from 0, starts at byte k×sk \times s, with ss taken from sizeof.
  • SEEK_SET, SEEK_CUR and SEEK_END measure the offset from the start, the current position and the end.
  • Use "r+b" to update in place, and put a positioning call such as fseek between a read and the following write.
  • In an uncached block model, a record that crosses a block boundary needs an extra block transfer.

Example: Locating records in a student-records file

A registrar's program stores student records in students.dat, a binary file with no header. Each record is one struct Student written with fwrite, and sizeof(struct Student) is 48 bytes on this system. Records are numbered from index 0. The file is 57,600 bytes long, and the disk transfers data in 4096-byte blocks numbered from 0.


a) What offset should the program pass to fseek with SEEK_SET to read the record with index 250?


Records 0 through 249 come before record 250, so 250 whole records of 48 bytes precede it:


offset(250)=250×48=12000 bytes\text{offset}(250) = 250 \times 48 = 12000\ \text{bytes}


The call is fseek(fp, 12000L, SEEK_SET), followed by fread(&s, sizeof s, 1, fp).


b) How many complete records does the file hold?


Divide the file size by the record size:


N=5760048=1200 recordsN = \frac{57600}{48} = 1200\ \text{records}


The division is exact, so there is no partial record at the end. The indices run from 0 to 1199. As a check, the last record starts at 1199 × 48 = ________ bytes and its final byte is 57552 + 47 = 57599, which is the last byte of the file.


c) Which disk block or blocks hold the record with index 85?


The record starts at 85 × 48 = ________ bytes. Its last byte is 4080 + 48 − 1 = ________. Byte bb lies in block ⌊b/4096⌋\lfloor b / 4096 \rfloor:


⌊40804096⌋=0⌊41274096⌋=1\left\lfloor \frac{4080}{4096} \right\rfloor = 0 \qquad \left\lfloor \frac{4127}{4096} \right\rfloor = 1


Block 0 covers bytes 0 to 4095 and block 1 covers bytes 4096 to 8191. Record 85 therefore spans two blocks: its first ________ bytes are in block 0 and its last ________ bytes are in block 1. In a simple model with no caching and one block per transfer, reading it from disk takes two block transfers. Caching, such as the operating system's page cache, can reduce the actual disk I/O.


d) The program has just read record 250 with fread. What fseek call using SEEK_CUR positions the stream at the start of record 249?


The read started at 12000 and transferred 48 bytes, so the position is now ________ bytes. Record 249 starts at 249 × 48 = ________ bytes. The relative offset is the target minus the current position:


11952−12048=−96 bytes11952 - 12048 = -96\ \text{bytes}


The call is fseek(fp, -96L, SEEK_CUR), which is two records back: one to undo the read just made and one more to reach record 249. Writing it as -2 * (long)sizeof(struct Student) keeps the code correct if the structure changes size. fseek(fp, 11952L, SEEK_SET) reaches the same place.

Match each term used when reading and writing binary files with random access in C to the description that fits it. Each description is used exactly once.

Match each term
A.

fseek origin that measures the offset from byte 0 of the file

B.

fseek origin that adds the offset to the size of the file

C.

Opening a stream with b in the mode string so no newline or end-of-file translation occurs

D.

Function that returns the current file position as a byte count from the start

E.

fseek origin that adds the offset to the current file position

F.

Reading or writing at any chosen byte offset without first processing the bytes before it

Random access

ftell

SEEK_CUR

SEEK_END

SEEK_SET

Binary mode

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A monitoring program appends fixed-length binary records of 72 bytes each to a log file, back to back from the first byte, with no header. You need to read the 1376th record in the file. What offset should you pass to fseek with SEEK_SET so that the next fread returns that record? Give the answer as an exact integer number of bytes.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A program must change the price stored in the record with index kk of an existing binary file of fixed-length records, read into a variable struct Item rec, while leaving every other record untouched. The price is edited in the in-memory copy between reading and writing; that edit is not listed. Put the remaining steps in the order the program should perform them.

  1. 1.

    Open the file with fopen(path, "r+b") and check that the result is not NULL.

  2. 2.

    Read the record with fread(&rec, sizeof rec, 1, fp) and check that it returned 1.

  3. 3.

    Write the edited copy with fwrite(&rec, sizeof rec, 1, fp).

  4. 4.

    Close the stream with fclose(fp) so any buffered bytes reach the file.

  5. 5.

    Call fseek(fp, -(long)sizeof rec, SEEK_CUR) to return to the start of record kk.

  6. 6.

    Call fseek(fp, k * (long)sizeof rec, SEEK_SET) to reach record kk.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice