使用包含数组的结构进行 fwrite
我如何写一个包含数组的结构
#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
谢谢
How do I fwrite a struct containing an array
#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;
}
The filesize of test.bin is 16 bytes, which I guess is (4+8) (int + double*). The filesize should be 4+10*8 (im on 64bit)
~$ 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
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在将指针(内存地址)写入文件,这不是您想要的。您想要写入指针引用的内存块(数组)的内容。这不能通过一次 fwrite 调用来完成。我建议您定义一个新函数:
您需要一个类似的 fread 替代品。
You are writing the pointer (a memory address) into the file, which is not what you want. You want to write the content of the block of memory referenced by the pointer (the array). This can't be done with a single call to fwrite. I suggest you define a new function:
You'll need a similar substitute for fread.
您的结构实际上并不包含数组,它包含一个指针。如果您确实想要可变长度结构,则需要在其中保留一个大小字段,以便您知道它有多大。 C FAQ 有一个示例,说明您正在尝试执行的操作。在您的情况下,它可能看起来像这样:
分配:
写入:
Your structure doesn't actually contain an array, it contains a pointer. If you really want variable-length structures, you'll need to keep a size field in there so that you know how big it is. The C FAQ has an example of exactly what it looks you're trying to do. In your case it might look something like this:
To allocate:
To write:
你的结构体包含一个指针,而不是一个 10 的数组。 sizeof() 会选择它。
你需要类似 fwrite(a.ary, sizeof(double), 10, of); 的东西为了写入实际的数组
Your structure contains a pointer, not an array of 10. the sizeof() picks that up.
You'll need something like fwrite(a.ary, sizeof(double), 10, of); in order to write the actual array
如果数组的大小始终为 10,则只需将结构更改为:
然后,您可以通过一次调用 fwrite 将其写出,使用 sizeof(refAry) 作为大小。
If the size of the array is always 10, then simply change your struct to:
You can then write this out with a single call to fwrite, using sizeof(refAry) for the size.