C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

RANDOM FILE ACCESS IN C

Random file access in C involves reading from or writing to a file at any desired position, rather than just sequentially from the beginning to the end.

fseek(): This function is used to set the file position indicator for the stream. It moves the file pointer to a specified location within the file.

int fseek(FILE *stream, long offset, int whence);
  • stream: Pointer to a FILE object that identifies the stream.
  • offset: Number of bytes to offset from the position specified by whence.
  • whence: Specifies the starting point for the offset calculation. It can take one of the following values:
    • SEEK_SET: Beginning of the file.
    • SEEK_CUR: Current position indicator.
    • SEEK_END: End of the file.

ftell(): This function returns the current file position indicator for the specified stream.

long ftell(FILE *stream);

stream: Pointer to a FILE object that identifies the stream.

Example: fseek() and ftell()

#include <stdio.h>
int main()
{
   FILE *filePointer;
   filePointer = fopen("sample.txt", "r");
    printf("The location of the current pointer is %d bytes from the start of the file\n", 
    ftell(filePointer));
   fseek(filePointer, 6, SEEK_SET);
   printf("The location of the current pointer is %d bytes from the start of the file\n", 
   ftell(filePointer));
   
    fclose(filePointer);
   return 0;
}

rewind(): This function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to calling fseek(stream, 0L, SEEK_SET).

void rewind(FILE *stream);

Example:

#include<stdio.h>  
#include<conio.h>  
void main()
{
  FILE *flptr;  
  char b;  
  clrscr();  
  flptr = fopen("myfile.txt","r");  
  while((c = fgetc(flptr)) != EOF){  
    printf("%c",b);  
  }  
  rewind(flptr); //puts the file pointer at the starting of the file.
  while((b=fgetc(flptr))!=EOF){
    printf("%c",b);
  }
  fclose(flptr);
  getch();
}