I'm developing a job in college, a system of cars, I'm having doubts on a specific function LoadLista
, here's the description of what it should do: "Load the file" cars.bin "in BINARY READING mode of the folder.
The first element of the file is the number of cars contained in the struct recorded in the list. (Use fread
)
Next you should do the malloc of the struct size and read the struct vector of the binary file. (Use fread)
*listaSize
- > pointer to a main variable where
the number of vector cars must be saved
return
- > Pointer to allocated memory
PS1: Close the program (exit (1)) If you can not open the file or allocate the memory
PS2: Before exiting the function, close the file
Carros *loadLista(int *listaSize){
Carros *ptr = NULL, *ini = NULL;
FILE *myfile = NULL;
*listaSize = 0;
myfile = fopen("carros.bin","rb");
if(myfile == NULL){
printf("Erro na abertura do arquivo\n");
printf("Saindo do programa...\n");
exit(1);
}
fread(listaSize,sizeof(int),1,myfile);
ptr = malloc((*listaSize)*sizeof(Carros));//alocando o vetor de structs.
if(ptr == NULL) //conforme o tamanho de (*listaSize)
{
printf("ERRO! Nao foi possivel alocar memoria\n");
printf("Saindo do programa...\n");
exit(1);
}
ini = ptr;
fread(ptr,sizeof(Carros),*listaSize,myfile);//leitura do vetor de struct
ptr = ini;
fclose(myfile);
return ptr;
}
The problem is, when I choose the option to print my list, it is always printing all the cars it has in the .bin file. I was not able to control this, type only 2, only 5 according to the size of listaSize
.