About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

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 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 

Actual Content from File :

Pritesh Abhiman Taral
Author of c4learn.com

Explanation of the Code :

Firstly open file in the read mode.
fp=fopen("test.txt","r");
Now we need to accept position number so that we can start reading from that position. We are moving file pointer to the last location using fseek() function and passing SEEK_END constant.
fseek(fp,0,SEEK_END);
Now we need to evaluate the current position of the file pointer.
len = ftell(fp);
ftell() will tell you the location of file pointer.
File Location = Total Number of Characters on File
We need to read last n characters from the file so we need to move pointer to (length-n) character back on the file. and from that location we need to read file.
fseek(fp,(len-n),SEEK_SET);

No comments: