Random Access of Files in C

Preview
You must first complete File Input output in C before viewing this Lesson




Random Access

We can randomly position file pointer at any position in the data file. There are two functions to do this:

  • fseek()
  • ftell()

1. fseek() function

fseek() function is used to take file pointer to a particular position data file. Syntax: fseek(Fpointer, Position, Initial);

Fpointer is name of file pointer variable.

Position number of characters  to be jumped.

Initial specifies the position from where file pointer should be jumped. It can three values :

0:  From the beginning of file.

1:  Current position.

2: End of file 

Program of fseek() function.
#include<stdio.h>
int main()
{
FILE *f1;
char line[80] , s;
int n;

f1=fopen(“data.txt”,”r”);
fgets(line,80,f1); 

printf(“%s”,line);

fseek(f1,2,0);
/*File pointer jumped to 3rd character from beginning*/

s=getc(f);   /*5th Character read from file*/
printf(“\n%c”,s);

fseek(f1,2,1);
/*File pointer jumped to 3rd character from current
position*/

s=getc(f);
printf(“\n%c”,s);

fseek(f1,0,2);
/*File pointer jumped end of file* /

s=getc(f);
printf(“\n%c”,s);

fclose(f);
return(0);
}

Output
Contents of file are=This is file
i
i




 2. ftell() function

This function tells the current position of file pointer .

Syntax:

ftell(Fpointer)

Fpointer is the name of file pointer variable.

 Program of ftell() function.
#include<stdio.h>
int main()
{
FILE *f;
char sentence[50];
char ch;
int n;
f=fopen(“contents.text”,”r”);

fgets(sentence,50,f); 
//To read a string value from a file

 

printf(“\nContents of file are=”);
printf(“%s”,sentence);

 

fseek(f,-1,2);
/*File pointer is placed at the Last character from the
end*/

 

n=ftell(f);  
/*Position of file pointer is stored in variable n.*/

 

printf(“\nFile pointer is at position %d”,n);
fclose(f);
return(0);
} 

Output
Contents of file are=i love india
File pointer is at position 11




Best Books of C

Lesson tags: File pointer and random access IN C, fseek() function in C, ftell() function in C, Random Access of Files in C
Back to: C Programming Language