Systems Programming

Laboratory: Low-Level I/O — lseek()

This laboratory will expose you to low-level I/O operations and random access operations.

Exercise 1

Write a program that uses low-level I/O calls to write some data to a file, seek a megabyte or so further ahead, write a short message, and then close the file.

Run your program and answer these questions:

  1. How big is the file as reported by ls -l?
  2. xxd the file and look at its structure. What data does the file appear to contain?
  3. How many blocks on disk does the file consume? Use the stat command in the shell.

Here is a program I wrote for this task.

Exercise 2

Read and understand Scott's code (available in Scott.tar) for reading and writing random pages in a file. The top-level code is in dbtest.c, which creates a database file and then enters a command loop that allows you to write and read individual blocks. It uses functions in random_rw.c to do the block reads and writes. page.h defines the page size and the page data structure. global_defs.h contains an enumeration type used to indicate a return status.

Play with the program, use xxd (or od if you prefer) and stat (the shell command). Enjoy!

Exercise 3

You can use random access to list a file backwards. Try it! After you've tried it, have a look at this solution (adapted from Rochkind, p. 109) that lists a file's lines in reverse order.


Author: Mark A. Sheldon
Modified: 20 March 2008