C Program to read file and print content in reverse order.
Objective
Write a C program to read a file and print its contents in Reverse order.
Algorithm / Approach
- Open the file in Read mode.
- Use
fseek(fptr, -1, SEEK_END)to move the file cursor to the very last character before the EOF. - Use
ftell(fptr)to get the exact numerical position (index) of the cursor. - Start a loop: read the character (
fgetc), print it. - Use
fseek(fptr, -2, SEEK_CUR)to jump the cursor back 2 spaces (becausefgetcautomatically pushed it forward 1 space). - Repeat until the cursor reaches position -1.
main.c
#include<stdio.h>
int main( ) {
FILE *fptr;
char ch;
int charIndex;
fptr = fopen("prowess.txt","r");
if(fptr != NULL) {
fseek(fptr,-1,SEEK_END);
charIndex=ftell(fptr);
do
{
ch = fgetc(fptr);
printf("%c",ch);
fseek(fptr,-2,SEEK_CUR);
charIndex--;
} while(charIndex!=-1);
return 0;
}
Expected Output
egaugnal elpmiS a si C
Explanation of the Program
- This program demonstrates Random Access File Handling in C.
- Instead of reading sequentially from start to finish,
fseek()allows you to manually place the cursor anywhere in the file. We place the cursor at the end, read a character, and manually force the cursor backwards, effectively reading the file in reverse.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)