How it works...

We will open the chosen file in read-only mode. If the file opens successfully, it will be pointed at by the file pointer fp. Next, we will find out the total number of lines in the file using the following formula:

total number of bytes used by the file/number of bytes used by one line

To know the total number of bytes used by the file, the file pointer will be positioned at the bottom of the file and we will invoke the ftell function. The ftell function finds the current location of the file pointer. Because the file pointer is at the end of the file, using this function will tell us the total number of bytes used by the file. To find the number of bytes used by one line, we will use the sizeof function. We will apply the preceding formula to compute the total number of lines in the file; this will be assigned to the variable, nol.

We will set a for loop to execute for nol number of times. Within the for loop, the file pointer will be positioned at the end of the last line so that all of the lines from the file can be accessed in reverse order. So, the file pointer is first set at the (-1 * size of one line) location at the bottom of the file. Once the file pointer is positioned at this location, we will use the fread function to read the last line of the file and assign it to the structure variable line. The string in line will then be displayed on the screen.

After displaying the last line on the screen, the file pointer will be set at the byte position of the second last line at (-2 * size of one line). We will again use the fread function to read the second last line and display it on the screen.

This procedure will be executed for the number of times that the for loop executes, and the for loop will execute the same number of times as there are lines in the file. Then the file will be closed.

Let's use GCC to compile the readrandominreverse.c program, as follows:

D:\CBook>gcc readrandominreverse.c -o readrandominreverse

If you get no errors or warnings, this means that the readrandominreverse.c program has been compiled into an executable file, readrandominreverse.exe.

Let's assume that we have a random file, random.data, with the following text:

This is a random file. I am checking if the code is working
perfectly well. Random file helps in fast accessing of
desired data. Also you can access any content in any order.

Let's run the executable file, readrandominreverse.exe, to display the random file, random.data, in reverse order using the following code:

D:\CBook>./readrandominreverse random.data
The content of random file in reverse order is :
desired data. Also you can access any content in any order.
perfectly well. Random file helps in fast accessing of
This is a random file. I am checking if the code is working

By comparing the original file with the preceding output, you can see that the file content is displayed in reverse order.

Now, let's move on to the next recipe!