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; }
ftellis the size in bytes. Not the size in the number of "elements". Now think about that and how you could get the number of "elements" from that size (hint: it involves division).int. If you want to useint32_tthen use it explicitly when and where you need it. Don't redefine (as macros) standard types or keywords.