I have a .dat file needs to be read and prints records for people that have the attributes specified as command line arguments. The format of the file is as follows. The records for each person begins with an unsigned 32-bit integer that contains various information about the person:
Bits
0-4 : length of first name (key=first)
5-9 : length of middle name (key=middle)
10-14 : length of last name (key=last)
15-21 : age (key=age)
22 : sex (0=male, 1=female) (key=sex)
23-28 : state (0 to 49 in alphabetical order) (key=state)
29 : currently married (0=false, 1=true) (key=married)
30 : employed full time (0=false, 1=true) (key=employed)
31 : attended college (0=false, 1=true) (key=college)
I think I suppose to read the whole 32-bit(4 bytes) first, then read bit by bit from the 32-bit integer. I am new to the fread and fseek so I really don't know if I am on the right track, any help will be appreciated. Here are my codes so far.
int main(int argc, char *argv[]) {
char *buf;
long lSize;
size_t result;
FILE *fp;
fp = fopen("/u1/junk/people.dat","r");
if(fp == NULL) {
printf("Error: can't open file to read\n");
return -1;
}
else {
printf("File people.dat opened successfully to read\n");
}
//obtian file size
fseek(fp, 0, SEEK_END);
lSize = ftell(fp);
rewind(fp);
//allocate memory to contain the whole file
buf = (char*) malloc (sizeof(char)*lSize);
while (!feof(fp)) {
fread(buf, 4, 1, fp);
fseek(fp, i, SEEK_CUR);
fread(buf, 32, 1, fp);
printf("%s\n", buf);
i+=32;
}
fclose(fp);
return 0;
}