如何将数组写入文件? [英] How do I write an array to a file?
问题描述
数组成员是否先后位于内存中?以下代码正确吗?
are array members successively located in memory? is the following code right?
int A[5] = {1, 2, 5, 7, 9};
file.write((char*)a, 5*sizeof(int));
推荐答案
如果您确定自己的"size"值正确,则可以这样做.假设结构是元素的简单结构,也可以用相同的方式编写结构.但是,当结构或数组包含指向对象的指针时,可能会带来复杂性.最好使用自行序列化的结构或类,这样在结构或类发生更改时无需更改代码.
You can do it this way if you are sure that your ''size'' value is correct; structures can also be written the same way, assuming they are simple structures of elemental items. However, complications can set in when structures or arrays contain pointers to objects. It is much better to use structures or classes that serialise themselves so that you do not need to change your code when the structure or class changes.
您的代码很好(几乎-见下文) .对于结构,基本相同.始终使用sizeof()
,因为编译器可能不会生成您可能认为的结构大小.
Your code is fine (almost - see below). For structures, basically the same. Usesizeof()
always, since the compiler might not generate the structure size you might think.
typedef struct xyz {
int a[5];
char b[7];
double c[2];
struct xyz *next;
char z;
} sxyz;
sxyz arr[8];
...
file.write(arr, sizeof(arr)); // right
file.write(&arr[0], 8 * sizeof(sxyz)); // wrong
请注意,我以两种不同的方式完成了两件事:
1.在这种情况下,arr
(作为指针)的含义与&arr[0]
相同-数组第一个元素的地址.这两个版本在这方面都是正确的.
2. (No of structs) * (size of struct)
不一定等于size of array of structs
作为练习,试着计算出上面的sxyz
大小的头部.将其与您的编译器所说的进行比较.
[可选的高级练习]查找在不破坏程序的情况下更改sxyz
大小的编译器选项.这对arr
的大小有什么作用?
干杯,
彼得
Note I''ve done two things in two different ways:
1. arr
in this context (as a pointer) means the same as &arr[0]
- the address of the first element of the array. Both versions are correct in this regard.
2. (No of structs) * (size of struct)
is not necessarily equal to size of array of structs
As an exercise, try and work out in your head the size of sxyz
above. Compare that with what your compiler says.
[optional advanced exercise]Find the compiler option that changes the size of sxyz
without breaking your program. What does that do to the size of arr
?
Cheers,
Peter
这篇关于如何将数组写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!