我正在尝试获取从二进制文件读取的结构数组的大小,以便我可以执行 for 循环来检索所有记录。
下面的代码能够以二进制形式读取文件并作为缓冲区返回。 然后缓冲区被“转换”为特征(结构)。
我尝试过 sizeof(features)/sizeof(struct feature_struct),它无法返回有效的计数,因此我可以将其用作 for 循环。
下面的代码我已将循环限制硬编码为 9 以下。其中 9 必须由系统动态检测。
提前致谢!
#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;
}
最佳答案
lSize/sizeof(struct feature_struct)???
假设它只包含struct feature_struct类型的数据
关于c - 从C中的结构数组中获取项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47245615/