我正在读取文件 *STL 中的结构,但结构是:
typedef struct
{
float x;
float y;
float z;
} point;
typedef struct
{
point normal_vector; //12 bytes
point p1; //12 bytes
point p2; //12 bytes
point p3; //12 bytes
short int notuse; //2 bytes
} triangle;
sizeof(triangle)
是 52—12+12+12+12+2+...2(不知道最后的 2 从哪里来?)文件 *STL 中每个单元的大小是 50(不是 4 的倍数)。
如何减少读取文件的结构大小(从 52 到 50)?
谢谢。
最佳答案
一种优于读取结构的方法 - 正如您所看到的,结构的内存布局可能会有所不同 - 减少其大小可能是可行的方法。
也就是说,您可以读取大块的文件并将数据剪切到您需要的部分。然后逐个字段读取数据并将数据放入目标数组中。类似的东西
float read_float(void ** data) {
float ** fp = data;
float ret = **fp; (*fp)++;
return ret;
}
point read_point(void ** data) {
point ret;
ret.x = read_float(data);
ret.y = read_float(data);
ret.z = read_float(data);
return ret;
}
int16_t read16(void ** data) {
int16_t ** i16p = data;
int16_t ret = **i16p; (*i16p)++;
return ret;
}
point read_triangle(void ** data) {
triangle ret;
ret.normal_vector = read_point(data);
ret.p1 = read_point(data);
ret.p2 = read_point(data);
ret.p3 = read_point(data);
ret.notuse = read_int16(data); // using short int is not portable as well as its size could vary...
return ret;
}
void * scursor = source_array; // which would be a char array
while (scursor < source_array + sizeof(source_array)) {
// make sure that there are enough data present...
target[tcursor++] = read_triangle(&scursor); // the scursor will be advanced by the called function.
}
这种方式(经过某些增强)也可以用于保留 e。 G。数字的字节序相同 - 对于要在平台之间交换的文件,最好是大字节序。对 read16
的更改很小,对 read_float
的更改稍大,但仍然可行。
关于c - 如何读取大小不是 4 倍数的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19740382/