How to do it…

  1. Define a structure consisting of a string member:
struct data{
char str[ 255 ];
};
  1. Open a random file in read-only mode and point at it with a file pointer:
fp = fopen (argv[1], "rb");
  1. The program will terminate if the file cannot be opened in read-only mode:
if (fp == NULL) {
perror ("An error occurred in opening the file\n");
exit(1);
}
  1. Find the total number of bytes in the file. Divide the retrieved total number of bytes in the file by the size of one record to get the total number of records in the file:
fseek(fp, 0L, SEEK_END); 
n = ftell(fp);
nol=n/sizeof(struct data);
  1. Use a for loop to read one record at a time from the file:
for (i=1;i<=nol;i++)
fread(&line,sizeof(struct data),1,fp);
  1. The content read from the random file is via the structure defined in step 1. Display the contents of the file by displaying the file content assigned to structure members:
puts(line.str);
  1. The end of the file is reached when the for loop has finished. Close the file pointer to release the resources allocated to the file:
fclose(fp);

The readrandomfile.c program for reading the content from a random file 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);
rewind(fp);
printf("The content in file is :\n");
for (i=1;i<=nol;i++)
{
fread(&line,sizeof(struct data),1,fp);
puts(line.str);
}
fclose(fp);
}

Now, let's go behind the scenes to understand the code better.