C - 创建一个没有 NULLs(未定义)元素的 bin 文件不起作用

C - Create a bin file without NULLs (non-defined) elements is not working

我在另一个结构数组中有一个结构数组,我想创建一个二进制文件,其中包含两个结构中的数据,但仅包含不为空的元素。

我的结构是:

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);
        }