C++ question, regarding reading info. and searching from a binary file

KeyserSoze

Diamond Member
Oct 11, 2000
6,048
1
81
Hey peoples, I hope someone can help me.

Ok, so I have to read in this binary file, no problem. Then, I have to search for each users ID to see if they exist or not. We have a struct, and the size of the struct is 56 bytes (I guess bytes.) And their ID is the FIRST value written in the file. Having a little problem on how to cycle through each record and search for the ID. I know how to search through Arrays, we just finished that. But having a little problem with this. Anyone have any clues?

If you need more info, lemme kno.


Thanx in Advance.



KeyserSoze
 

HigherGround

Golden Member
Jan 9, 2000
1,827
0
0
the following code writes the 5 element foo struct into a binary file ...


#include <stdio.h>

struct foo
{
unsigned int id;
unsigned int ss;
char name[32];
};

int main(void)
{
FILE* fp = fopen("filename.bin", "wb");
foo f[] = { { 234, 116294094, "tom" },
{ 235, 116214054, "rob" },
{ 236, 123224494, "jim" },
{ 237, 111294044, "ann" },
{ 238, 176254514, "bob" }
};
fwrite(f, sizeof(foo), 5, fp);
}


the following code reads it ( and while reading compares the ids to the argument passed in to the program ) ...


#include <stdio.h>
#include <stdlib.h>

struct foo
{
unsigned int id;
unsigned int ss;
char name[32];
};

int main(int argc, char* argv[])
{
FILE* fp = fopen("filename.bin", "rb");
foo f;
if(argc > 1)
{
int id = atoi(argv[1]);
while(!feof(fp) && fread(&f, sizeof(foo), 1, fp) > 0)
if(f.id == id)
{
printf("found entry with id %d\n", id);
return 0;
}
}

return 1;
}


I hope you can connect the dots :p