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

C Programming Tutorial - Random Access File Handling

By David Bolton, About.com

7 of 9

Example of Random Access File Storage

How you use it is up to you- you could for example have a file full of equal size records. If these records have a size of 100 then record 0 occupies bytes 0-99, record 1 occupies bytes 100-199 etc. More generally record n starts at (n-1)*sizeof(record).

Download Example 2.

This shows an index and data file pair storing strings in a random access file. The strings are differing lengths and are indexed by position 0, 1 etc.

Though it would be easy to store this in one structure in a file and read it all into memory, this isn't always possible due to memory limitations.

How It Works

There are two void functions: CreateFiles() and ShowRecord(int recnum). CreateFiles uses a char * buffer of size 1100 to hold a temporary string made u of the format string msg followed by n asterisks where n varies from 5 to 1004. Two FILE * are created both using wb filemode in the variables ftindex and ftdata. After creation these are used to manipulate the files. The two files are
  • index.dat
  • data.dat
The index file holds 1000 records of type indextype; this is the struct indextype which has the two members pos (of type fpos_t) and size. The first part of the loop
sprintf(text,msg,i,i+5);
for ( j=0; j<i+5; j++)
  strcat(text,"*");
populates the string msg like this
This is string 0 followed by 5 asterisks :*****
This is string 1 followed by 6 asterisks :******
and so on. Then this
index.size = (int)strlen(text) ;
fgetpos(ftdata, &index.pos ) ;
populates the struct with the length of the string and the point in the data file where the string will be written.

On the next page : More on Example 2

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

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Example of Random Access File Storage

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

All rights reserved.