C Program To Read Last n Characters Of The File Using Appropriate File Function

How To Write a C Program to read last n characters from the file . Open a file in read mode. Accept value of n .  in C Programming Language ?

Solution For C Program To Read Last n Characters Of The File Using Appropriate File Function:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int n;
long len;
clrscr();
printf("Enter the value of n : ");
scanf("%d",&n);
fp=fopen("test.txt","r");
if(fp==NULL)
    {
    puts("cannot open this file");
    exit(1);
    }

fseek(fp,0,SEEK_END);

len = ftell(fp);

fseek(fp,(len-n),SEEK_SET);

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

fclose(fp);
getch();
}

Output :

Enter the value of n : 4
.com 

Tags: C Program To Read Last n Characters Of The File Using Appropriate File Function, c fwrite, reading a file in c, c fopen, c fprintf, c open, write ac program to display the contents of a file in reverse order, c fread, c file io.


Learn More :