我在其他结构数组中有一个结构数组,我想创建一个包含此数据的二进制文件(只有不为空的元素)。
我的结构是:
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'
为什么会这样?
最佳答案
看起来这里发生了一些事情。这里有一些重要的事情要注意。totalViajes
在struct cliente
中的位置
要在fwrite()中写入的字节数
在再次读取文件之前重置FILE*
。
这是我用来测试你想要的东西。
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 {
int totalViajes;
char dni[30+1];
char nombre[30+1];
char apellidos[30+1];
char direccion[30+1];
struct viaje viajes[50];
} clientes[20];
int main()
{
clientes[0].totalViajes = 1;
clientes[0].viajes[0].numeroNoches = 52;
int totalClientes = 1;
FILE* fp_guardarCargarEstado = fopen("myFile.bin", "wb");
// For create bin file
for (int i = 0; i < totalClientes; i++) {
fwrite(&clientes[i], sizeof(struct cliente)-(sizeof(struct viaje)*50), 1, fp_guardarCargarEstado);
for (int j = 0; j < clientes[i].totalViajes; j++) {
fwrite(&clientes[i].viajes[j], sizeof(struct viaje), 1, fp_guardarCargarEstado);
}
}
fclose(fp_guardarCargarEstado);
// set variables to 0 so you can tell if the read actually does anything
clientes[0].totalViajes = 0;
clientes[0].viajes[0].numeroNoches = 0;
fp_guardarCargarEstado = fopen( "myFile.bin", "rb" );
// For read bin file
for (int i = 0; i < totalClientes; i++) {
fread(&clientes[i], sizeof(struct cliente)-(sizeof(struct viaje)*50), 1, fp_guardarCargarEstado);
for (int j = 0; j < clientes[i].totalViajes; j++) {
fread(&clientes[i].viajes[j], sizeof(struct viaje), 1, fp_guardarCargarEstado);
}
}
fclose(fp_guardarCargarEstado);
printf("%i\n%i", clientes[0].totalViajes, clientes[0].viajes[0].numeroNoches );
return 0;
}
关于c - C-使用fwrite在另一个结构数组中创建一个结构数组的bin文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49157517/