c - 从C中的结构数组中获取项目数

标签 c arrays struct

我正在尝试获取从二进制文件读取的结构数组的大小,以便我可以执行 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/

相关文章:

Swift UnsafePointer<T>(data.bytes).memory 在某些(但不是全部)情况下崩溃

c - 为什么没有标准的 memswap 函数

objective-c - 如何编写 'clamp'/'clip'/'bound' 宏以返回给定范围内的值?

c - 在C中打印待处理信号队列中的阻塞信号

python - 使用 python 将动态列表/数组存储在数据库中

c++ - C++中数组的动态调整大小

javascript - 获取给定索引的数组的下一个和上一个元素

c - 如何找出声明 C 结构的位置?

c - 是否有任何工具可以确定程序在运行时进入哪些功能?

c - C中的嵌套动态结构?