1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Random Access File Handling

By , About.com Guide

6 of 9

Programming Random Access Files

The main reason for using binary files is the flexibility you get; you can read or write anywhere in the file. Text files only really let you read or write sequentially. These days with the prevalence of cheap or free databases such as SQLite or MySql, there is less of a need to use random access on binary files. That is for another lesson though. In a sense, random access file records is a little old fashioned but still useful.

I've used various data handling schemes based on random access files in the past before databases were prevalent. For instance with small files I used a index/data file pattern. This consisted of two files. One is the data file and holds a number of records that can vary in length. The other file is an index file and has the same number of records as the data file. In the index file though each record is the same length and consists of two parts which fit into a struct.

struct {
  fpos_t pos;
  int size;
} indexrec;
The type fpos_t is implementation defined and used in fsetpos() and fgetpos(). These are the more modern versions of fseek and ftell and are most useful for creating bookmarks. If you are calculating a file position and need to set it then you should use fseek() and likewise ftell() to give you the int current position.

In reality fpos_t is probably just an int but you should use type fpos_t for portability. It holds a copy of the current file pointer. This is a property of a random access file that says where the next read or write takes place and is zero based. It has a granularity of 1 so you can position it any any point in the file.

On the next page : An Example of Random Access Strings

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Programming Random Access Files

©2009 About.com, a part of The New York Times Company.

All rights reserved.