Could you tell me where im doing it wrong...why it doesn't work correctly?
Here's my Binary saving file:
int SaveToBinary(FILE *fp,struct node *kvartiras){
int l;
struct node *tmp=NULL;
for(tmp=kvartiras; tmp; tmp = tmp->next){
l=fwrite(&(tmp->s),1,sizeof(Kvartira),fp);
if (l != (sizeof(Kvartira))) {
printf("\nгрешка - неуспешно записване на данните !");
return 1;
}
}
system("cls");
return 0;
}
Reading from Binary file:
struct node * ReadBinary(FILE *fp,struct node *kvartiras){
struct node *tmp=NULL;
struct node *tmp2=NULL;
int l;
if((kvartiras) && (kvartiras->next)) {
*tmp = *kvartiras;
*tmp2 = *kvartiras->next;
}
while(tmp2) {
free(tmp);
tmp=tmp2;
tmp2 = tmp2->next;
}
rewind(fp);
while(!feof(fp))
{
tmp=(struct node*) malloc(sizeof(struct node));
if(!tmp){
printf("\nГрешка при заделяне на паметта !\n");
return kvartiras;
}
l=fread(&(tmp->s),1,sizeof(Kvartira),fp);
if (l != (sizeof(Kvartira)))
{
free(tmp);
return kvartiras;
}
tmp->next=kvartiras;
kvartiras=tmp;
}
return kvartiras;
}
This is the cases which im using:
case 6:
if(kvartiras){
for(i=0;i<256;i++) check[i]='\0';
fflush(stdin);
printf("\nВъведете име на файл:");
scanf_s("%s",check);
fp_out= fopen(check,"wb");
if(fp_out)
{
if(!(SaveToBinary(fp_out,kvartiras))){
//-- извикване на ф-я за запис на данните в двоичен файл --
printf("\nданните са записани във файл <%s> успешно !",check);
if(fp_out) fclose(fp_out);
}
}else printf("\nгрешка - неуспешно създаване на файла !");
}else printf("\nгрешка - базата данни е празна !");
break;
case 7:
for(i=0;i<256;i++) check[i]='\0';
fflush(stdin);
printf("\nВъведете име на файл:");
scanf_s("%s",check);
fp_in=fopen(check,"rb");
if(fp_in){
kvartiras=ReadBinary(fp_in,kvartiras);
//-- извикване на ф-я за прочитане на данни от двоичен файл --
if(kvartiras) printf("\nданните са прочетени успешно !");
if(fp_in) fclose(fp_in);
}else printf("\nгрешка - неуспешно създаване на файла !");
break;
}
}while (mode != 8 );
return 0;
}
And the structure:
typedef struct {
int kod;
char adres[51];
int plo6t;
int stai;
int naem;
} Kvartira;
struct node {
Kvartira s;
struct node *next;
};
There is probably one mistake :
if (l != (sizeof(Kvartira)))
This will always be true, sizeof(Kvartira) is at least sizeof(int) * 4 + 51.
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.