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

C Programming Tutorial - Random Access File Handling

By , About.com Guide

8 of 9

More on Example 2

At this point both the index file struct and the data file string can be written to their respective files. Note that although these are binary files they are written sequentially. In theory you could write records to a position beyond the current end of file and I think the operating system will extend the file but it's not a good technique to use and probably not in the slightest bit portable.

The final part is to close both files. This ensures that the last part of the file gets written to disk. During file writes, many of the writes don't go directly to disk but are held in fixed sized buffers. Once a write fills the buffer then the entire contents of the buffer are written to disk.

There is a file flush function that forces flushing and you can also specify file flushing strategies but those are intended for text files and will be covered in the next tutorial.

ShowRecord Function

Having written the two files, it's useful to test that we can retrieve any specified record from the data file. For this we need to know two things:
  1. Where it starts in the data file.
  2. How big it is
This is what the index file does. The ShowRecord function opens both files, seeks to the appropriate point ( recnum * sizeof(indextype) and fetches a number of bytes = sizeof(index).
fseek( ftindex, sizeof(index)*(recnum) ,SEEK_SET ) ;
fread( &index,1,sizeof(index),ftindex) ;
SEEK_SET is a constant that specifies where the fseek is done from. There are two other constants defined for this.
  • SEEK_CUR - seek relative to current position
  • SEEK_END - seek absolute from the end of the file
  • SEEK_SET - seek absolute from the start of the file
You could use SEEK_CUR to move the file pointer forward by sizeof(index).
fseek( ftindex, sizeof(index) ,SEEK_SET ) ;

On the next page : More about 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. More on Example 2

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

All rights reserved.