facebook like button

04 June, 2011

program 57: reading a file in reverse order in C

The need:
    This is a simple program to show functions to traverse through a file. This program shows how ftell() and fseek() functions are used to move file pointer through a file. this program first takes some text input from user and prints to a file. Then the program tells the position of each character in the file and prints the file contents in reverse order on the terminal.

The code:
-------------------------------------------- 
#include<stdio.h>
main()
{
    FILE *fp;
    int i,j;
    char c;
    fp=fopen("RANDOM.txt","w");
    printf("Enter the file contents to write to.\n");
    while((c=getchar())!='\n')
    putc(c,fp);
    j =ftell(fp);
    printf("Number of characters entered = %d\n", j);
    fclose(fp);
    i=0;
    fp=fopen("RANDOM.txt","r");
    while(feof(fp)==0)
    {
        fseek(fp,i,0);
        if((c=getc(fp))!=EOF)
        printf("position of %c is %d\n",c,ftell(fp));
        i++;
    }
    printf("\nReversrd order.\n");
    fseek(fp,-1,1);
    do
        {
        printf("%c",getc(fp));
        }
    while((fseek(fp,-2,1))==0);
    putchar('\n');
    fclose(fp);
}

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

The approach:
    First run the program after that try to understand the code. This program is intended to illustrate the use of feof(), fseek() and ftell() functions. feof() returns 0 if end of file has not reached else return non-zero. The function fseek() introduced in post59 is illustrated here. The function ftell() returns the relative position of a file pointer from the beginning of the file. Taking text and printing that to file is trivial. getchar() takes a character from the user and putc() can write a character to the file. For printing the file in reverse order first we move our file pointer to last printable character ( because the last character of every file is EOF by default which is neither printable nor do we want it to be printed.)
    One important point which I skipped in previous posts is: "the file pointer is automatically incremented accordingly as it goes on reading data. For example the file pointer is automatically incremented by one if a character is read from the file." So each time we print a character the pointer points to the character next to it. So to print a file in reverse order we start scanning from last printable character and each time go 2 character back to scan character left to just scanned character.


Remarks:

1. This program is inspired from the example 12.5 of the book "Let us C" by Balagurusamy.

1 comment:

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply