Reputation: 15
I am trying to get the size of a struct array read from a binary file so that I can do a for loop to retrieve all the records.
The code below is able to read the file in binary form and return as a buffer. The buffer is then "Cast" as a features(struct).
I have tried sizeof(features) / sizeof(struct feature_struct), it fails to return a valid count so that I can use it as with for loop.
The code below I have hardcoded the loop limit to below 9. Where 9 have to be dynamically detect by the system.
Thanks in advance !.
#include <stdio.h>
#include <stdlib.h>
/* the maximum length of a feature identifier (including the terminating null) */
#define MAX_ID 12
/* the maximum length of a feature name (including the terminating null) */
#define MAX_NAME 256
typedef int int32_t;
typedef struct feature_struct {
char type; /* feature type */
char id[MAX_ID]; /* unique identifier */
char name[MAX_NAME]; /* name */
int32_t xloc; /* x location */
int32_t yloc; /* y location */
int32_t xdim; /* x dimension */
int32_t ydim; /* y dimension */
} FEATURE;
int main(){
int n;
struct feature_struct* features;
FILE *fptr;
long lSize;
FEATURE* buffer;
size_t result;
if ((fptr = fopen("structsFile.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
//exit(1);
}
// obtain file size:
fseek (fptr , 0 , SEEK_END);
lSize = ftell (fptr);
rewind (fptr);
buffer = malloc ( sizeof(struct feature_struct) * lSize );
result = fread (buffer,1,lSize,fptr);
if (result != lSize) {
fputs ("Reading error",stderr);
}
features = buffer;
for (int i = 0; i < 9; i++){
printf("%s\n", features[i].name);
}
fclose(fptr);
/*
for(n = 1; n < 5; ++n)
{
fread(&features, sizeof(struct feature_struct), 1, fptr);
printf("name: %s\n",features.name);
printf("location: %c\n", features.type);
}
*/
return 0;
}
Upvotes: 0
Views: 463
Reputation: 331
lSize/sizeof(struct feature_struct)???
Assuming it contains only data of type struct feature_struct
Upvotes: 1