Random Access Files

 

A “Random Access File” (hereafter RAF) is a file in which one can read a given record without reading the previous records.  There are various types of RAF and the one we’ll be looking at will have fixed sized records in each file.  Also we will read the records as character strings.

 

Here are some functions you’ll want to have and comments on what they should do:

 

int fopen_ra(char * file_name, int record_length)

Opens a file for reading and writing.  Creates it if it doesn’t exist.  Enters the information about name, file descriptor, and record size into a table.  I’ll call this table the file table).  Returns the place in the table where this information is stored.

 

char * read_ra(int file_number, int record_number)

Checks if that file is open by checking the file table.  Does an lseek to get to the proper record.  Reads the number of characters indicated by the file table record size.  Returns the character string read.

 

int write_ra(int file_number, int record_number, char * write_string)

Checks if the file is open by checking the file table.  Does an lseek to get to the place to write.  Writes the string write_string into the file (pad with null characters or truncate excess).  Return the number of characters written; return negative numbers for errors such as the file not being open.

 

void close_ra(int file_number)

Closes the file thus freeing the position in the table.

 

Place all of the above functions and the file table into a file.  The file table should be “static” so that the only way it can be accessed is through the above functions.

 

To test this you’ll need to have some test program or programs.  Here’s some pseudo-code that shows the kind of testing that I have in mind:

            main(){

                        int i;

                        char q[100]

                        char *p=q

                        i= fopen_ra(“foo”, 40);

                        while (k<num) {

                                    readline(data_string)

                                    write_ra(i, k, data_string)

                        }

                        p=read_ra(i,10)

                        printf(“%s”,p)

                        close(i)

i= fopen_ra(“foo”, 40);

write_ra(i, 10, “New data”)

                        p=read_ra(i,10)

            }

 

 

Due next Tuesday (Feb 28).