Random access/Direct access files:
In general we access the data from a file character by character or record by record from the beginning of the file to the end of file called sequential access. If the size of file is so small then takes reasonable time to get the required record but takes time if a file has 1000’s of records.
Say for example, a file has 10000 records and has to get 9999th record then we have to all the way go through 9999 records to get the required record, results take a lot of time.
We can overcome this by directly accessing a record from the required position. It can be done in two steps that are, sending the file active pointer to the required position using fseek() and reading the record using fread() as we learned in the previous session.
fseek() function:
It is the function used to send the file pointer to the specified position from the specified position.
fseek() function
According to the function definition, it accepts three arguments those are
File pointer
“offset” specifies the number of bytes to be skipped to locate a record
“Whence” specifies from where “offset” is measured.
“whence” must be 0 if we want to specify the beginning of file (BOF)
It returns zero on successfully reaching to the required position otherwise returns a non-zero
Note: Random or direct access can be performed only on binary files
Let us see an example to get more clarity