Program to reading data from text file || File handling || C programming
In this, we are going to see a program in which we will read last 'n' characters from a file in C Programming Language.

//Program to read last n characters from a file

#include <stdio.h>
#include <stdlib.h>

void main()
{
    FILE *fp;
    char a;
    int n;
    long len;

    printf("Enter the value of n : ");
    scanf("%d", &n);

    fp = fopen("d:\\Program 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);
}

#ENJOY CODING


Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post