包含数组的结构的fwrite

时间:2010-02-08 17:51:26

标签: c++ struct fwrite fread

如何编写包含数组的结构

#include <iostream>
#include <cstdio>

typedef struct {
  int ref; 
  double* ary;
} refAry;

void fillit(double *a,int len){
  for (int i=0;i<len;i++) a[i]=i;
}

int main(){
  refAry a;
  a.ref =10;
  a.ary = new double[10];
  fillit(a.ary,10);
  FILE *of;
  if(NULL==(of=fopen("test.bin","w")))
     perror("Error opening file");
  fwrite(&a,sizeof(refAry),1,of);

  fclose(of);
  return 0;
}

test.bin的文件大小为16个字节,我猜是(4 + 8)(int + double *)。文件大小应为4 + 10 * 8(即64位)

~$ cat test.bin |wc -c
16
~$ od -I test.bin 
0000000                   10             29425680
0000020
~$ od -fD test.bin -j4
0000004   0,000000e+00   7,089709e-38   0,000000e+00
                     0       29425680              0
0000020

感谢

4 个答案:

答案 0 :(得分:2)

您正在将指针(内存地址)写入文件,这不是您想要的。您想要写入指针(数组)引用的内存块的内容。只需调用一次fwrite即可完成此操作。我建议你定义一个新函数:

void write_my_struct(FILE * pf, refAry * x)
{
    fwrite(&x->ref, sizeof(x->ref), 1, pf);
    fwrite(x->ary, sizeof(x->ary[0]), x->ref, pf);
}

你需要一个类似的替代fread。

答案 1 :(得分:1)

您的结构实际上不包含数组,它包含指针。如果你真的想要可变长度的结构,你需要在那里保留一个大小字段,以便你知道它有多大。 C FAQ有一个例子,它正是你想要做的。在你的情况下,它可能看起来像这样:

typedef struct {
    int ref; 
    double ary[1];
} refAry;

#define SIZE_OF_REFARY (sizeof(refAry) - sizeof(double))

分配:

size_t alloc_size = SIZE_OF_REFARY + 10*sizeof(double);
refAry *a = malloc(alloc_size);
a->ref = 10;

写:

fwrite(a, SIZEP_OF-REFARY + a->ref * sizeof(double), 1, file);

答案 2 :(得分:0)

你的结构包含一个指针,而不是一个10的数组.sizeof()选择了它。

你需要像fwrite(a.ary,sizeof(double),10)之类的东西;为了写出实际的数组

答案 3 :(得分:0)

如果数组的大小始终为10,那么只需将结构更改为:

typedef struct {
  int ref; 
  double ary[10];
} refAry;

然后你可以通过一次调用fwrite来编写它,使用sizeof(refAry)作为大小。

相关问题