Random Access in File

Random Access in File

Published by: Nuru

Published date: 21 Jun 2021

Random Access in File Photo

Random Access in File

Random access means you can move to any part of a file and read or write data from it without having to read through the entire file. There is no need to read each record sequentially if we want to access a particular record. C supports these functions for random access file processing.

Functions used for random access file are:

  • fseek()
  • ftell()
  • rewind()

fseek()

  • This function is used for seeking the pointer position in the file at the specified byte.
  • Syntax:  fseek( file pointer, displacement, pointer position);
    Where
    ->file pointer: It is the pointer that points to the file.
    ->displacement: It is positive or negative. This is the number of bytes that are skipped backward (if negative) or forward (if positive) from the current position. This is attached to L because this is a long integer.
  • Pointer position: This sets the pointer position in the file.
    SEEK_SET     Seeks from the beginning of the file
    SEEK_CUR    Seeks from the current position
    SEEK_END    Seeks from the end of file

Equivalently,

Value Pointer position
0 Beginning of file
1 Current position
2 End of file

 

  1. fseek( p,10L,0) or fseek(fp,10L, SEEK_SET);
    0 means pointer position is on the beginning of the file, from this statement pointer position is skipped 10 bytes from the beginning of the file.
  2. fseek( p,5L,1) or fseek(fp,5L,SEEK_CUR);
    1 means the current position of the pointer position. From this statement pointer position is skipped 5 bytes forward from the current position.
  3. fseek(p,-5L,1) or fseek(fp,-5L,SEEK_CUR);
    From this statement pointer position is skipped 5 bytes backward from the current position.

Example: fseek()
#include
int main()
{
FILE * fp;
f = fopen("myfile.txt", "w");
fputs("Hello World", fp);
fseek(fp, 6, SEEK_SET);
fputs(" Nepal", fp);
fclose(fp);
return 0;
}

ftell()

  • This function returns the value of the current pointer position in the file.
  • The value is count from the beginning of the file.
  • Syntax: ftell(fptr); Where fptr is a file pointer.

Example:

#include
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}

rewind()

  • This function is used to move the file pointer to the beginning of the given file.
  • Syntax: rewind( fptr); Where fptr is a file pointer.

 

More Examples:

Random Access in File

Random Access in File