Reputation: 159
I have a file from which I want to read data previously created by another program but I get an segmentation fault error. This is the programm.
typedef char Telemento[MAX_CHAR+5];
typedef struct{
Telemento arraycola[NUM_ELEM];
int inicio;
int final;
}TCola;
typedef char TNombreImpresora[MAX_NOM_IMPR];
typedef struct{
TNombreImpresora nombreimpresora;
int numerodeficherosencola;
TCola colaImpresora;
}TImpresora;
typedef struct{
TImpresora impresora;
int ocupado;
}TCelda;
typedef TCelda Tlistaimpresora[MAX_IMPR];
int main(){
FILE *fp;
int i=0;
Tlistaimpresora listaimpresoras;
fp=fopen("test.bin", "r");
while(feof(fp)==0 && i<4){
fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), (i+1), fp);
listaimpresoras[i].ocupado=1;
i++;
}
fclose(fp);
return 0;
}
Thanks for your time. If anyone needs more info please tell me.
Upvotes: 0
Views: 117
Reputation: 16540
This line:
fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), (i+1), fp);
is a bit odd for a couple of reasons:
1) your only reading one instance of the struct
2) the real sizeof should be the sizeof the struct, not the sizeof some array entry.
suggest:
fread(&listaimpresoras[i].impresora, sizeof(Tlistaimpresora), 1, fp);
Also, the code is very obfuscated by the messy typedef declarations All these typedef's will make the code much more complicated than necessary. just define one struct with the appropriate number of instances for each field (or group of fields)
Upvotes: 0
Reputation: 12392
replace (i+1)
with 1
in the fread
call
also change [1]
to [i]
what you have happening is each read getting bigger and the last read overflowing the array.
what you want is each read the same size into a different array element.
Upvotes: 0
Reputation: 53006
Just change this
fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), (i+1), fp);
with this
fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), 1, fp);
you are not reading i + 1
items, just 1
.
Upvotes: 3
Reputation: 1091
I think this line has an error (should be 1
, not i+1
):
fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), 1, fp);
Upvotes: 3