C Program to Read last n characters from the file

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)

--------------------------------------------------------------------------------------------------------------------------

#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);
}

--------------------------------------------------------------------------------------------------------------------------

Output

--------------------------------------------------------------------------------------------------------------------------

Enter the Value of n : 2
.com
Actual Content from File
File Handling in C
Basic C.com



EmoticonEmoticon