Random Access
There are two predefined functions in C language to provide random access in files:
- fseek()
- ftell()
1. fseek()
fseek() function can be used to take file pointer to a particular position inside a file.
Syntax: fseek(Pointer, Position, Starting);
Pointer is name of file pointer.
Position is number of characters to be jumped.
Staring specifies the position from where file pointer should start. There are three values :
0: Beginning of file.
1: Current position.
2: End of file
Program of fseek() function. |
#include<stdio.h> int main() { FILE *f1; char str[80] , s; int n; f1=fopen(“data.txt”,”r”); printf(“%s”,str); fseek(f1,2,0); s=getc(f); fseek(f1,2,1); s=getc(f); fseek(f1,0,2); s=getc(f); fclose(f); |
Output |
Contents of file are=This is file i i |
2. ftell() function
This function provides the current file pointer position.
Syntax:
ftell(Pointer)
Pointer is the name of file pointer variable.
Program of ftell() function. |
#include<stdio.h> int main() { FILE *f; char str[50]; char ch; int n; f=fopen(“data.txt”,”r”); fgets(str,50,f); printf(“\nContents of file are=”); fseek(f,-1,2);
n=ftell(f);
printf(“\nFile pointer is at position %d”,n); |
Output |
Contents of file are=i love india File pointer is at position 11 |