Random access C

Till now we have read from a file and written to a file. But all operations were performed serially.Apart from just reading the records and writing them, we may need to process the records. It may be desirable to add new records to the file (either at the end or in between somewhere), delete existing records, and modify contents of existing records or to rearrange the record. The operations can be performed with ease if we can access the file at random.

We know that
fread, reads the record where the pointer is currently placed and advances pointer by one record. fwrite, writes the record where the pointer is currently placed.

We have a few functions which help us access the file records at random.

rewind (fpt) :-This function places the pointer to the beginning of the file irrespective of where it is present right now.
void rewind(FILE *fp);

ftell(fpt) = This function tells where the pointer is positioned right now. It returns this pointer as a long integer which is an offset from the beginning of the file. returns -1L on error
long ftell(FILE * fp);

fseek = This function lets us move the pointer from one record to another.
fseek(FILE *fp, long offset, int reference)
The first argument is the file pointer. Second argument is the offset which tells the compiler by how many bytes should the pointer be moved from a particular position. And the third argument is the reference from which the pointer should be offset. It can be

SEEK_END: move the pointer from end of file.
SEEK_CUR: move the pointer w.r.t. current position.
SEEK_SET: move the pointer w.r.t. beginning of file.

fseek return 0 if successful or nonzero on failure.

To move the pointer to previous record from its current position, we can use

fseek(fpt, -recsize, SEEEK_CUR);
(-recsize)moves the pointer back by recsize bytes from the current position

fseek(fpt, -recsize, SEEK_END);
This fseek would place the pointer beyond the last record in the file. 0 is the offset.

fgetpos = Gets current file pointer position.
int fgetpos(FILE * fp, fops_t *pos)
Position stored in *pos can be passed to fsetpos to set the file pointer. Returns 0 on success otherwise
nonzero.

fsetpos = Position the file pointer on file.
int fsetpos(FILE *fp, const_t *pos)
New position pointed to by pos is the value obtained by a previous call to fgetpos. On success return 0
on failure returns a nonzero value.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics