My goal is to create a list from "menu.bin". This is the func:
pitem recupera_menu(pitem p){
pitem novo,aux;
FILE *f;
f=fopen("menu.bin","rb");
if(f == NULL)
printf("Erro ao caregar o ficheiro 'menu.bin' \n");
novo = (struct item*)malloc(sizeof(item));
if(novo == NULL)
return p;
novo->prox=NULL;
while((fread(novo,sizeof(item),1,f))!=NULL){
if(p==NULL){
p=novo;
aux=p;
}
else{
aux->prox=novo;
aux=aux->prox;
}
printf("%s\n OLE\n",aux->id);
}
fclose(f);
system("pause");
return p;
}
this is my struct:
typedef struct item item, *pitem;
struct item{
char id[5];
int ing[10];
float qtd[10];
pitem prox;
};
For some reason the result of the file isn't the one that should be(it doesn't read the document strait).Maybe someone could help me.
EDIT: well it does run, and prints the "ole" line.The problem is that the file .bin has been completed with the following struct type:
struct item{
char id[5];
int ing[10];
float qtd[10];}
and when i do malloc, i allocate memory to the folowing struct type:
struct item{
char id[5];
int ing[10];
float qtd[10];
pitem prox;
};
struct item{
char id[5];
int ing[10];
float qtd[10];
};
struct list{
struct list *next;
struct item payload;
};
Allocate:
struct list *p;
p = malloc (sizeof *p);
read from file:
ret = fread(&p->payload, sizeof p->payload, 1, fp);
Extra: sanitize the loop:
int recupera_menu(struct list **pp){
int ret,cnt;
FILE *fp;
fp = fopen("menu.bin","rb");
if (!fp) {
fprintf(stderr, "Erro ao caregar o ficheiro 'menu.bin' \n");
return 0;
}
for (cnt=0; ;cnt++) {
*pp = malloc(sizeof **pp);
if( !*pp ) break;
(*pp)->next = NULL;
ret = fread(&(*pp)->payload, sizeof &(*pp)->payload, 1, fp);
if (ret < 1) break;
pp = &(*pp)->next;
}
free (*pp);
*pp = NULL;
fclose(fp);
return cnt
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.