- Open the random file in read-only mode using the following code:
fp = fopen (argv[1], "rb");
- If the file does not exist or does not have enough permissions, an error message will be displayed and the program will terminate, as shown in the following code:
if (fp == NULL) {
perror ("An error occurred in opening the file\n");
exit(1);
}
- To read the random file in reverse order, execute a loop equal to the number of lines in the file. Every iteration of the loop will read one line beginning from the bottom of the file. The following formula will be used to find out the number of lines in the file:
total number of bytes used in the file/size of one line in bytes
The code for doing this is as follows:
fseek(fp, 0L, SEEK_END);
n = ftell(fp);
nol=n/sizeof(struct data);
- Because the file has to be read in reverse order, the file pointer will be positioned at the bottom of the file, as shown in the following code:
fseek(fp, -sizeof(struct data)*i, SEEK_END);
- Set a loop to execute that equals the number of lines in the file computed in step 3, as shown in the following code:
for (i=1;i<=nol;i++)
- Within the loop, the file pointer will be positioned as follows:
Figure 6.2
- To read the last line, the file pointer will be positioned at the byte location where the last line begins, at the -1 x sizeof(line) byte location. The last line will be read and displayed on the screen, as shown in the following code:
fread(&line,sizeof(struct data),1,fp);
puts(line.str);
- Next, the file pointer will be positioned at the byte location from where the second last line begins, at the -2 x sizeof(line) byte location. Again, the second last line will be read and displayed on the screen.
- The procedure will be repeated until all of the lines in the file have been read and displayed on the screen.
The readrandominreverse.c program for reading the random file in reverse order is as follows:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct data{
char str[ 255 ];
};
void main (int argc, char* argv[])
{
FILE *fp;
struct data line;
int n,nol,i;
fp = fopen (argv[1], "rb");
if (fp == NULL) {
perror ("An error occurred in opening the file\n");
exit(1);
}
fseek(fp, 0L, SEEK_END);
n = ftell(fp);
nol=n/sizeof(struct data);
printf("The content of random file in reverse order is :\n");
for (i=1;i<=nol;i++)
{
fseek(fp, -sizeof(struct data)*i, SEEK_END);
fread(&line,sizeof(struct data),1,fp);
puts(line.str);
}
fclose(fp);
}
Now, let's go behind the scenes.