How to search a binary save file?

Ok I think I understand how to save information to a binary file but how do you recall a certain record in a binary file. For Example:

A address book, you have a person's name with information attached to it and you want to save this information to the binary file so you can recall this information, how do you look up that information in the binary file?

Thanks
You either have to make records fixed size (say N) so that record #R is located at byte offset (R * N) within the file (R being zero based) or you have to start at the beginning of the file and read each record sequentially until you get to the one you want.

[There are other more complex databasey type solutions that I've ignored].
a simple example (using C but the principle is the same)

1
2
3
4
5
6
7
8
9
10
11
12
13

typedef struct {
   char name[32];
   char address[48];
} rec_t;

rec_t Rec;

FILE *fp = fopen( "myfile.bin", "rb"); // open file in binary mode
fseek( fp, 3L*sizeof(rec_t),  SEEK_SET ); // set file ptr to fourth record
fread( &Rec, sizeof(Rec), 1, fp ); // read the record
fclose(fp);


Topic archived. No new replies allowed.