Random Access of Files in C Language | fseek() function in C Language | ftell() function in C Language

You must first complete Data File Handling in C Language before viewing this Lesson

Random Access of Files in C Language | fseek() function in C Language | ftell() function in C Language

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”);
  fgets(str,80,f1);    printf(“%s”,str);  fseek(f1,2,0);
/*File pointer jumped to 3rd character from beginning*/

  s=getc(f);   
  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 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); 
//To read a string value from a fileprintf(“\nContents of file are=”);
printf(“%s”,str);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

 

Spread the love
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
Spread the love