Thursday 8 January 2009

Programming Random Access File I/O in C++

This lesson is about using random access files in C++ and the next lesson will look at working with text files. Apart from the simplest of applications, most programs have to read or write files. Maybe it's just for reading a config file, a text parser or something more sophisticated. As with many C++ programs, some people prefer the old C way of doing things and if that is you, see the C Tutorial on Programming Random Access Files. This tutorial will however be more about the C++ way of implementing it though example 1 is just a wrapper class around C functions.

The basic file operations are

  • open - open a file- specify how its opened (read/write) and type (binary/text)
  • close - close an opened file
  • read - read from a file
  • write - write to a file
  • seek - move a file pointer to somewhere in a file.
There are two fundamental types of file: text and binary. Of these two, binary are generally the simpler to deal with. As doing random access on a text file isn't something you need to do too often, we'll stick with binary files for the rest of this lesson.

The first four operations listed above are for both text and random access files. The last one just for random access which means we can move to any part of a file and read or write data from it without having to read through the entire file. Back thirty years or forty years ago, much data was stored on large reels of computer tape. The only way to get to a point on the tape was by reading all the way through the tape. Then disks came along and it became easy and fast to read from or write to any part of a file.

0 comments: