Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to read file and print content in reverse order.

C Code Example — File Handling Programs

ADVERTISEMENT

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

  1. Open the file in Read mode.
  2. Use fseek(fptr, -1, SEEK_END) to move the file cursor to the very last character before the EOF.
  3. Use ftell(fptr) to get the exact numerical position (index) of the cursor.
  4. Start a loop: read the character (fgetc), print it.
  5. Use fseek(fptr, -2, SEEK_CUR) to jump the cursor back 2 spaces (because fgetc automatically pushed it forward 1 space).
  6. 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)
ADVERTISEMENT