Write a C program to read last n chatacters of the file using appropriate file function
Problem Statement : Write a C Program to read last n characters from the file . Open a file in read mode. Accept value of n .
#include<stdio.h> void main() { FILE *fp; char a; 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); } /* Move the file pointer to end of file */ fseek(fp,0,SEEK_END); /* Read the length of the file */ len = ftell(fp); /* Move the file pointer at the beginning of last n characters */ fseek(fp,(len-n),SEEK_SET); do { a=fgetc(fp); putchar(a); }while(a!=EOF); fclose(fp); getch(); }
Output :
Enter the value of n : 4 .com
Actual Content from File :
Pritesh Abhiman Taral Author of c4learn.com