C Program to Read Last n Characters from File

C Program to Read Last n Characters from File:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().



#include<stdio.h>
#include<stdlib.h>
main()
{

   FILE *fp;
   char ch;
   int num;
   long len;

   printf("Enter how many characters : ");
   scanf("%d",&num);

   fp=fopen("fil.txt","r");  //Accepting file for reading
   if(fp == NULL)
    {
      puts("\nCannot open file");
      exit(1);
    }

   fseek(fp,0,SEEK_END);
   len=ftell(fp);
   fseek(fp,(len-num),SEEK_SET);

   do
    {
      ch=fgetc(fp);
      putchar(ch);
    }while(ch != EOF);

   fclose(fp);
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

13 + 8 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.