C Programming language

How to use random access File in C: fseek( ) Function
Previous Home Next

Random Access to file in C

Random access means we can move to any part of a file and read or write data from it without having to read through the entire file. we can access the data stored in the file in two ways.

  1. Sequentially
  2. Randomly

Some points about Sequentially and Randomly accessing of Files

  • If we want to access the forty fourth record then first forty three record read sequentially to reach forty four record
  • In Random access data can be accessed and processed directly
  • If there is no need to read each record sequentially then use Randomly access
  • If we want to access a particular record random access takes less time than the Sequential access

C supports these function for random access file.

  1. fseek( ) Function
  2. ftell ( ) Function
fseek() Function

This function is used for setting the file position pointer at the specified bytes . fseek is a function belonging to the ANCI C standard Library and included in the file <stdio.h>. Its purpose is to change the file position indicator for the specified stream.

int fseek(FILE *stream_pointer, long offset, int origin);

Argument meaning

stream_pointer is a pointer to the stream FILE structure of which the position indicator should be changed;

offset is a long integer which specifies the number of bytes from origin where the position indicator should be placed;

origin is an integer which specifies the origin position. It can be:

  • SEEK_SET: origin is the start of the stream
  • SEEK_CUR: origin is the current position
  • SEEK_END: origin is the end of the stream

/* * Program to understand the use of fseek function */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emprecord
{
	char name[30];
	int age;
	float sal;
}emp;
void main()
{
	int n;
	FILE *fp;
	fp=fopen("employee.dat","rb");
	if (fp==NULL)
	{
	printf("/n error in opening file");
	exit(1);
	}
	printf("enter the record no to be read");
	scanf("%d",&n);
	fseek(fp,(n-1)*sizeof(emp),0);
	freed(&emp,sizeof(emp),1,fp);
	printf("%s\t,emp.name);
	printf("%d\t",emp.age);
	printf("%f\n",emp.sal);
	fclose(fp);
	getch();
};
Previous Home Next