Question

i have this while cicle and i need print only the registries where the apagado variable='\0'.

my structure is:

typedef struct {

char apagado; 
char prop[MAXPLEN];
char mat[6];
double valor;
} veiculo_t;

... sample of code:

{
    FILE *f=fopen("veic.dat", "rb");
    veiculo_t *t = malloc(sizeof(veiculo_t));
    while(fread(t, sizeof(char), sizeof(*t), f))
    print_registry(t); //
   }          

with this code prints all the registries, independently the value of apagado.

Was it helpful?

Solution

Wrong use of parameters:

while(fread(t, sizeof(char), sizeof(*t), f))

Should be

while(fread(t, sizeof(*t), 1, f))

The first returns values0 ... sizeof(*t).. The second returns 0 ... 1. So to prevent a partially filled structure, use the 2nd form.

while(fread(t, sizeof(*t), 1, f)) {
  if (t->apagado == '\0') {
    print_registry(t); //
  }
}

Of course, make certain f and t are not NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top