Position a Text File to a Desired Character using the functions fseek() and ftell(). - C File

C examples for File:Text File

Description

Position a Text File to a Desired Character using the functions fseek() and ftell().

Demo Code

#include <stdio.h>

int main()//from   ww w  .j a  va  2 s .c  o  m
{
     FILE *fptr;
     int m, n, k, p;
     fptr = fopen("C:\\Code\\pune.txt", "r");
    
     if(fptr != NULL){
          puts("File opened successfully");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          printf("Let us read a single character and it is: ");
          m = fgetc(fptr);
          putchar(m);
          printf("\n");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          fseek(fptr, 8, 0);
          puts("Statement \"fseek(fptr, 8, 0);\" executed");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          fseek(fptr, 3, 1);
          puts("Statement \"fseek(fptr, 3, 1);\" executed");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          fseek(fptr, -5, 1);
          puts("Statement \"fseek(fptr, -5, 1);\" executed");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          fseek(fptr, -3, 2);
          puts("Statement \"fseek(fptr, -3, 2);\" executed");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          fseek(fptr, 0, 2);
          puts("Statement \"fseek(fptr, 0, 2);\" executed");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          puts("Now let us perform a read operation");
          m = fgetc(fptr);
          printf("Value read is %d\n", m);
          n = ftell(fptr);
          printf("Now value of n is still %d\n", n);
          fseek(fptr, 0, 0);
          puts("Statement \"fseek(fptr, 0, 0);\" executed");
          n = ftell(fptr);
          printf("Now value of n is %d\n", n);
          puts("That's all.");
        
          k = fclose(fptr);
          if(k == -1)
              puts("File-closing failed");
          if(k == 0)
              puts("File closed successfully.");
     }else
           puts("File-opening failed");
    
     return(0);
}

Result


Related Tutorials