C :- Binary File - Random accessing

The information stored in a binary file can also be accessed as randomly. It means any of the record can be accessed directly by using the following functions

1.fseek()

2.ftell()

fseek() :-

The purpose of this function is to move the file pointer on the specified location

Syntax :fseek(FilePointer,Offset,Origin)
Offset is the no of bytes to move either forward or backward direction. If the offset is +ve It means move into forward direction and if it is –ve then move into backward direction. The offset must be a long integer value.
Origin is the place from where the offset will be measured such as follows

Origin Meaning
0 Beginning of the file
1 Current Position
2 End of the file.

Example :

fseek(fptr,(long)50,0);
fseek(fptr,(long)-10,1);
fseek(fptr,(long)-22,2);
fseek(fptr,(long)0,0);

ftell() :-

The purpose of this function is to recognise the position of accessing pointer from the beginning of the File. This function returns a long integer value
Syntax :ftell(FilePointer);
long a = ftell(fptr);

P1 : Write a program to display the no of records avliable in the file "Student.bin".

#include<stdio.h>
#include<conio.h>
struct student
{
	int rollNo;
	char name[20];
	int m1,m2;
};

void main()
{
	FILE *fptr;
	int nRecords;
	long position;
	fptr = fopen("C:\\CPrograms\\BinaryFile\\Student.bin","rb");
	fseek(fptr,(long)0,2);
	position = ftell(fptr);
	nRecords = position/sizeof(struct student);
	fclose(fptr);
	printf("No of Records =%d",nRecords);
}

P2 : Write a program to accept a record no from the user and display the information of that record. If that record is not aviliable then display error message that "Record not found".

#include<stdio.h>
#include<conio.h>
struct student
{
	int rollNo;
	char name[20];
	int m1,m2;
};
struct student std;
int main()
{
	FILE *fptr;
	int nRecords,recNo;
	long position;
	fptr = fopen("C:\\CPrograms\\BinaryFile\\Student.bin","rb");
	fseek(fptr,(long)0,2);
	position = ftell(fptr);
	nRecords = position/sizeof(struct student);
	printf("Enter the record no=");
	scanf("%d", &recNo);
	if(recNo<=nRecords)
	{
		fseek(fptr,(long)(recNo-1)*sizeof(std),0);
		fread(&std,sizeof(std),1,fptr);
		printf("%d\t %s\t %d\t %d\n",std.rollNo,std.name,std.m1,std.m2);
	}
	else
	{
		printf("record is not found");
	}
	fclose(fptr);
	
	return 1;
}

About Company

TechiesEra is a quality Training Center of Noida. TechiesEra provides summer training in Noida on Hadoop, MongoDB,CouchDB,NoSql,Dot Net, Android, Java,PHP etc with live projects. TechiesEra is group of highly qualified professionals in the field of IT education & recruitments.

Get in Touch

  • Phone: +91-9821384666
    9560231801 / 9711965544
    0120 - 4292580
  • Email:
    info@TechiesEra.com
  • Address:
    C-33, Sector - 2
    Near By : Niruala Hotel
    Noida - 201301