C Program to Read last n characters from the file.
⦁ The C library function int fseek(FILE *stream, long int offset, int whence) sets the file position of the stream to the given offset.
⦁ Following is the declaration for fseek( ) function.
int fseek(FILE *stream, long int offset, int whence)
⦁ Stream is the pointer to a FILE object that identifies the stream.
⦁ Offset is the number of bytes to offset from whence.
⦁ Whence is the position from where offset is added. It is specified by one of the following constants.
SEEK_SET - Beginning of file.
SEEK_CUR - Current position of the file pointer
SEEK_END - End of file.
--------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
int main( )
{
FILE *fp;
char ch;
int num;
long length;
printf("Enter the value of num : ");
scanf("%d", &num);
fp = fopen("test.txt","r");
if(fp == Null)
{
puts("cannot open this file");
exit(1);
}
fseek(fp,0,SEEK_END);
length = ftell(fp);
fseek(fp, (length-num), SEEK_SET);
do
{
ch = fgetc(fp);
putchar(ch);
} while(ch! = EOF);
fclose(fp);
return(0);
}
--------------------------------------------------------------------------------------------------------------------------
Explanation
--------------------------------------------------------------------------------------------------------------------------
⦁ Open file in the Read mode.
fp = fopen("test.txt","r");
⦁ We are moving file pointer to the last location using fseek( ) function and passing SEEK_END constant.
fseek(fp,0,SEEK_END);
⦁ Now evaluate the current position of the file pointer.
length = ftell(fp);
⦁ ftell( ) will tell you the location of file pointer.
File Location = Total Number of Characters on File
⦁ To Read last n characters from the file we need to move pointer to (length-n) character back on the file. and from that location we need to read file.
fseek(fp, (length-num), SEEK_SET);
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Enter the Value of n : 2
.com
Actual Content from File
File Handling in C
Basic C.com
EmoticonEmoticon