How to navigate a binary file in C Programming

/*
* Program to navigate a binary file
* From the book: C Programming Visual Quickstart Guide
*
* A random point in the data file is used to
* return a "lucky number."
*/

#include <stdio.h>
/*
* For rand() and srand().
*/
#include <stdlib.h>
/*
* For time(), used with srand().
*/
#include <time.h>

/*
* Set the file path and name.
*/

#define THEFILE "numbers.dat"

/* 
* Numbers of items being written.
* Creat a constant macro representing
* the number of items in the array.
*/

#define ITEMS 50

int main(void) {

/* 
* Need a pointer of type FILE
*/

FILE *fp;

/*
* Two integers are required.
* The first integer will be used as the
* off-set: the location within the number
* file to move to. The second will store 
* the read-in number value.
*/

int offset, number;

/*
* Attempt to open the file for binary reading.
*/

fp = fopen(THEFILE, "rb");

/*
* Start a conditional based on the file pointer.
* The file is open.
*/

if (fp != NULL) {

/*
* Find a random offset in bytes.
* The first line seeds the rand() funcion.
* The second line picks an arbitrary offset,
* as a random number up to the number of items
* stored. After this second line of code, offset
* will be qual to a number between 0 and 49, 
* corresponding to the 50 items originally stored
* in the file (like an array though, we begin
* counting at 0.)
* The third line multiplies the value of offset
* by the size of an integer. This is neccessary
* because we need to specify the offset in bytes.
* For example, if the randomly generated value is 
10, then the offset needs to be 40 bytes: 10 times
* sizeof(int), normally 4 bytes.
*/

srand((unsigned)time(NULL));
offset = rand() % ITEMS;
offset *= sizeof(int);

/* 
* Move to the random location and read in a number.
* The first line moves the virtual marker offset
* bytes into the file, starting from the beginning
* of the file. The second line reads one bk of data
* of sizeof(number) bytes and stores this in the 
* number variable. Remember that the fread() 
* function takes an address of a variable as its 
* first argument, so &number is used (the memory
* addres of the number variable.)
*/

fseek(fp, offset, SEEK_SET);
fread(&number, sizeof(number), 1, fp);

/*
* Print the number.
*/

printf("Your lucky number is: %d.\n", number);

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1;
}

/*
* Close the file.
*/

if (fclose(fp) != 0){
printf("The file could not be closed.\n");

}

/* 
* Pause.
*/

getchar();

return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *