我在另一个结构数组中有一个结构数组,我想创建一个二进制文件,其中包含两个结构中的数据,但只包含不为空的元素。
我的结构是:
struct viaje {
char identificador[30+1];
char ciudadDestino[30+1];
char hotel[30+1];
int numeroNoches;
char tipoTransporte[30+1];
float precioAlojamiento;
float precioDesplazamiento;
};
struct cliente {
char dni[30+1];
char nombre[30+1];
char apellidos[30+1];
char direccion[30+1];
struct viaje viajes[50];
int totalViajes;
} clientes[20];
接下来我正在尝试:
// For create bin file
// 'totalClientes' is a var which contain the number of 'clientes'
for (i = 0; i < totalClientes; i++) {
fwrite(clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado);
// 'clientes[i].totalViajes' is a var which contain the number of 'viajes' inside actual 'cliente'
for (j = 0; j < clientes[i].totalViajes; j++) {
fwrite(clientes[i].viajes[j], sizeof(struct viaje), 1, fp_guardarCargarEstado);
}
}
// For read bin file
for (i = 0; i < totalClientes; i++) {
fread(clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado);
for (j = 0; j < clientes[i].totalViajes; j++) {
fread(clientes[i].viajes[j], sizeof(struct viaje), 1, fp_guardarCargarEstado);
}
}
但是它将所有元素创建到 bin 文件中,包括空元素。怎么了?
为什么会这样?
谢谢。
最佳答案
这是因为包含结构 cliente
在您的案例中包含静态分配的结构 viaje
的 50 个元素数组。
fwrite(clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado);
行自动写入 cliente
对象中存在的所有元素,即,它写入 50元素数组 vijae
也。
因此这段代码是多余的:
for (j = 0; j < clientes[i].totalViajes; j++) {
fwrite(clientes[i].viajes[j], sizeof(struct viaje), 1, fp_guardarCargarEstado);
}
您正在编写的元素已由语句编写: `fwrite(clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado); 这是预期的行为。
如果您不希望这种行为,请创建一个临时对象,例如:
struct cliente_temp {
char dni[30+1];
char nombre[30+1];
char apellidos[30+1];
char direccion[30+1];
//struct viaje viajes[50]; omit this line or use a pointer struct viaje *viajes;
int totalViajes;
} clientes[20];
并在写入文件和从文件读取之前将原始结构复制到此结构。然后你可以使用代码编写结构 vijae :
for (j = 0; j < clientes[i].totalViajes; j++) {
fwrite(clientes[i].viajes[j], sizeof(struct viaje), 1, fp_guardarCargarEstado);
}
关于C - 创建一个没有 NULLs(未定义)元素的 bin 文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49158088/