-
Reading a binary file
This is probably very simple, but I need to know where I'm going wrong.
I have a structure and a binary file containing lots of records. I want to read one record from the file into the structure, use the information in the structure, and then read another record (the next one) from the file into the structure.
This is my code:
#define REC_SIZE(sizeof(a_rec))
typedef struct{
char...;
char...;
float...;
int...;
}a_rec;
FILE *fp;
void main()
{
a_rec cust_rec;
a_rec *a_rec_ptr = &cust_rec;
/*open file*/
fread(a_rec_ptr, REC_SIZE, 1, fp);
/*then use data in structure, then read next record for use*/
fread(a_rec_ptr, REC_SIZE, 1, fp);
fclose(fp);
}
Why won't it read the next record in the binary file? The file pointer continues to point at the beginning of the same record.
-
fread returns a success/fail status - check it.
If it returns fail, use feof() and ferror() to work out why.
-
?Reading a binary file
The way to increment the pointer is to place fread in a while loop that will stop looping when you are at the end of the file and have read in the last record. FREAD returns the number of items read in, in your case 1. When the end of the file is reached FREAD can no longer return 1. So the loop stops.
while( fread( a_rec_ptr, REC_SIZE, 1, fp) == 1 )
{
/*then use data in structure, then read next record for use*/
}
In your coding you have declared a structure of type a_rec and then declared an identifier called cust_rec. With this in mind you might want to fread directly into the identifier cust-rec
If so ?while( fread( a_rec_ptr, REC_SIZE, 1, fp) == 1 )? would be replaced with
while( fread(&cust_rec, REC_SIZE, 1, fp) == 1 )
{
}
Good luck
Stephanos