C Program to Read last n characters from the file !
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 .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #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 :
1 2 | Enter the value of n : 4 .com |
Actual Content from File :
1 2 | Pritesh Abhiman Taral Author of c4learn.com |
Explanation of the Code :
Firstly open file in the read mode.
1 | 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.
1 | fseek(fp,0,SEEK_END); |
Now we need to evaluate the current position of the file pointer.
1 | length = ftell(fp); |
ftell() will tell you the location of file pointer.
1 | 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.
1 | fseek(fp, (length - num), SEEK_SET); |