Topic :Random Access Files in C++ Programming Language: Reading | Writing | Modifying | Deleting |Searching:


In This Tutorial, We are Introduction the concept of Random file Access. Unlike Sequential files, we can access Random Access files in any order we want. Think of data in a Random Access file as we would songs on a compact disc or record, we can go directly to any song we want without having to play or fast-forward over the other songs. If we want to play the first song, the sixth song, and then the fourth song, we can do so. The order of play has nothing to do with the order in which the songs were originally recorded. Random-file access sometimes takes more Programming but rewards our effort with a more flexible file-access method .

Random file access enables us to read or write any data in our disk file without having to read or write every piece of data before it. We can Quickly search for data, Modify data, delete data in a random-access file. We can open and close Random access file same like Sequential files with same opening mode, but we need a few new functions to access files randomly, we find that the extra effort pays off in flexibility, power, and speed of disk access:

image: Sequential Access Vs Random Access:

The process of randomly accessing data in a file is simple. Think about the data files of a large credit card organization. When we make a purchase, the store calls the credit card company to receive authorization. Millions of names are in the credit card company’s files. There is no quick way the credit card company could read every record sequentially from the disk that comes before Ours. Sequential files do not lend themselves to quick access. It is not feasible, in many situations, to look up individual records in a data file with sequential access.

The credit card companies must use a random file access so their computers can go directly to our record, just as we go directly to a song on a compact disk or record album. The functions we use are different from the sequential functions, but the power that results from learning the added functions is worth the effort.

When our program reads and writes files Randomly, it treats the file like a big Array. with Arrays, we know we can add, print, or remove values in any order. we don't have to start at the first array element, Sequentially looking at the Next one, Until we get the Element we need. We can view our Random-access-file in the same way, accessing the data in any order. In Random Access file, we can:

  • » We Can Read from Anywhere from the file.
    » We Can Write to Anywhere in the file.
    » We can Modify our record:
    » We can Search any Record from file
    » And we can Delete Any record from file:

File-Pointer: File-pointer is an special type of pointer that is used to keep track of the current read/write position within the file. when something is read from the file or written to file, the reading/writing happens at the file pointer's current location. By default, when opening a file for reading or writing, the file pointer is set to the beginning of the file. However, if a file is opened in append mode, the file pointer is moved to the end of the file.

For doing this all operation, we have just one Important things that we need to know about before Move on. The thing is file-pointer, this File-Pointer move sequentially but we can also make it to move Randomly using some function. C++ provide us four function, using these function can help us to set this file-pointer to any where in the file:

Each file have associated two pointers known as the "Input-Pointer", and "Output-Pointer". The Input Pointer is used to reading the contents of a given file location and the Output Pointer is used for writing to a given file location.

Special function to move File-Pointer within the File:
fileObject.seekg(long_num,  origin);
We can move input pointer to a specified location for reading by using this function. fileObject is the pointer to the file that we want to access. long_num is the number of bytes in the file we want to skip. and origin is a value that tells to compiler, where to begin the skipping of bytes.
fileObject.seekp(long_num,  origin);
We can move Output pointer to a specified location by using this function. it's same like seekg() Function but in Case of writing:
This function return the current position of Input pointer. this function don't need any argument.
This function return the current position of Output pointer. this function don't need any argument.


Each File have two Associated pointer known as

  • » Input pointer: Used for reading the content of a given file location.
    » Output Pointer Used for Writing the content of a given file location.

seekg() Function allow us to move the Input Pointer to specified location for reading purpose within the file. The Syntax for seekg() function is:

fileObject.seekg(long_num,  origin);

  • In above Syntax:

    » fileObject is the pointer to the file that we want to access.
    » long_num is the number of bytes in the file we want to skip. Compiler does not read this many bytes, but literally skips the data by the number of bytes specified in long_num. Skipping the bytes on the disk is much faster than reading them. if long_num. is negative, Compiler skips backward in the file that allows for rereading of data several times. Because data files can be large, we must declare long_num. as a long integer to hold a large amount of bytes.
    » origin is the value that tells Compiler, where to begin the skipping of bytes specified by long_num. Origin can be any of the three values shown in the Table below.

fileObject.seekg(0,   ios::beg);
Go to Start: No matter how far into a file we have read, by using this Syntax, the file-pointer will back to the beginning of the file.
fileObject.seekg(0,   ios::cur);
Stay at Current Position: Using this syntax, the file-pointer will show its current position.
fileObject.seekg(0,   ios::end);
Go to End of the file: using this syntax, the file-pointer will point to end of the file.

Error Handling:

In our each example, we are trying to use error checker to avoid error, and it's really good for us and for our program. C++ provides it's self some function, which can help us to reduce our error in our program.

Some Important Methods for Error Handling:
bad()Returns True if an Error occurs while reading or writing Operation. (Example: in case we try to write to a file that is not open for writing or if the device where we try to write has no space left).
fail()Returns true in the same cases as bad() plus in case that a format error happens. (as trying to read an integer number and an alphabetical character is received:).
eof()Returns true if a file opened for reading has reached the end.
good()Return False in the same cases in which calling any of the previous functions would return true.

Some More useful Function
Function NameSyntaxExplanationExample
write( (char *) &Obj,  sizeof(Obj));
This function is used with Output-Pointer object to write the Block of data. Write() Function uses the binary version of data instead of the text version. when write() is used, each value is stored in its binary format and each record is created to have a fixed length. The write function takes three arguments, first is Pointer to Character, the second is Address of the object, and last the size of Object.
read( (char *) &Obj,  sizeof(Obj));
This function is used with Input-Pointer object to read the block of data. It's same like read() Function, but in sense of reading.
This Function is used to remove any file from record. it take one argument, which is the file Name to be delete.
rename(Old_Name,  New_Name);
This function is used to rename any file. it take two argument, first is the Old Name of file, and the other is New name for that file.

C++ Supports Random-Access files with several functions: these Functions include error Checking, file pointer Positioning, and the Opening and closing of files. Now we have the complete toolkit to write any data on our disk for storage and retrieval.

I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.