When is it better to use random-access ? When is it not?

When is it better to use sequential-access? When is it not?

So far I'm only sure to use random access in a situation where I'm dealing with a fixed number of records. For example a record of rooms in a hotel.

8 Years
Discussion Span
Last Post by Ancient Dragon

Random access is for when you can't predict the access pattern or you can't deterministically work out a pattern to organize your data for sequential access. Sequential access is for when you don't care about the order of records, can predict the access pattern or organize your data to fit a sequential pattern, or the access medium doesn't support random access.


If the data contains random-length records or lines then you have no other choice but to use sequential access. As always, there are a few exceptions, such as if you create an index file that contains the offsets to the beginning of each line or record, but probably goes beyond the scope of what you have in mind. Records in sequential files can not normally be changed without rewriting the entire file.

Sequential access is also used when you want to just read the contents of the entire file. This is done whether the length of each record is fixed or random. Files written to be random access can be read sequentially, but not vice versa.

Random access is used when each record or each line is exactly the same size. Then the program can calculate the exact location of any record in the file and seek to that location. You can't do that with most text files except as noted above. The program can easily change the contents of any given record because it has a fixed length.

Votes + Comments
Very clear explanation

What method would be most suitable for a logging file? The data would be of the same length and the program would be reading from the file on a moments notice to generate a report but the file would be constantly appended with information at the end as the user performs certain functions with the program.


The way I wrote logging files was to open and close the file for each log entry. I know it takes a lot of cpu time to do that but it gives other processes a change to jump in and copy or read the file. The logger checks to see when it can open the file for output and exclusive access. If it fails then it sleeps a little while and tries again.

That doesn't matter whether it is a sequential of fixed-length binary file. It all depends on what you want to write in that file.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.