the following has poped up while studying and I would like whether it does what it is supposed to. Let's say we have the following struct:
typedef struct a{
int x;
int y;
}a;
And we have a binary file where we can find info about multiple instances of the above struct, and we want to have an array of these structs and fill them one by one. Can we do the following?
a* aStruct= malloc(sizeof(a)*10); // aStruct[10]
a* temp;
int i = 0;
while(i < 10){
temp = aStruct+i++;
fread(&temp->x, sizeof(int), 1, inputFile);
fread(&temp->y, sizeof(int), 1, inputFile);
}
Does the above means that in the end, the array aStruct will be filled with the contents from the file? If not, how can we do it?
<stdint.h>), as you will probably know the size of each integer in the binary file, so that it isn't dependent on a specific implementation ofint.forloop is more natural for this code.struct, generalizing could lead to the possibility of padding in the struct. Then thereadwould depend on how the file was written -- the answers given so far (including OP's) would work for sequentially written members or structs with no padding. However, a struct written with padding would have to be read astructat a time on an architecture with similar padding requirements, or have the padding handled explicitly.