Random Access To File


There is no need to read each record sequentially, if we want to access a particular record.C supports these functions for random access file processing.

  1. fseek()
  2. ftell()
  3. rewind()


fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer.

Pointer position:
This sets the pointer position in the file.


Value          pointer position
0			Beginning of file.
1			Current position
2	 		End of file


Ex:

1) fseek( p,10L,0)

0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file.

2)fseek( p,5L,1)

1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position.

3)fseek(p,-5L,1)

From this statement pointer position is skipped 5 bytes backward from the current position.

ftell()

This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.

rewind()

This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.

Example program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we need fseek() and fgetc()).

#include<stdio.h>
#include<conio.h>
void main()
{
     FILE *fp;
     char ch;
     clrscr();
     fp=fopen("file1.c", "r");
     if(fp==NULL)
     	printf("file cannot be opened");
     else
     {
	    	printf("Enter value of n  to read last ‘n’ characters");
	    	scanf("%d",&n);
	    	fseek(fp,-n,2);
	    	while((ch=fgetc(fp))!=EOF)
	     	{ 
	        	 printf("%c\t",ch);
	      	}
      }
	fclose(fp);
	getch();
}


OUTPUT: It depends on the content in the file.