我在其他结构的数组中有一个结构的数组,我想创建一个包含此数据的二进制文件(只有元素不为空)。
我的结构是:
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
for (i = 0; i < totalClientes; i++) {
fwrite(clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado);
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);
}
}
我还没有尝试过 fread
,因为我在 fwrite
中遇到了两个错误:error: incompatible type for argument 1 of 'fwrite'
和 注意:应为 'const void *' 但参数类型为 'struct cliente'
为什么会这样?
最佳答案
fread
和fwrite
函数将指向内存位置的指针作为它们的第一个参数。您传递的是一个结构的实例。
您需要使用寻址运算符&
传入此结构的地址。此外,无需单独编写 struct viaje
实例,因为它们已经包含在 struct cliente
// For create bin file
for (i = 0; i < totalClientes; i++) {
fwrite(&clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado);
}
// For read bin file
for (i = 0; i < totalClientes; i++) {
fread(&clientes[i], sizeof(struct cliente), 1, fp_guardarCargarEstado);
}
关于C - 使用 fwrite 在其他结构数组中创建一个结构数组的 bin 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49157517/