This code dose not produce any errors. It creates list and fills is, then saves to file and try to load. I tryed to printf the content loaded from file. Works fine. But is it podssible to do such a way
read one structure from file and use it to fill new structure? till the end of file
Also I wounder does my clear memory function work?
Code:
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
#include <string.h>
struct item
{char name[20];int prc; int col;
struct item *prev;
struct item *next;
};
void build(void);
void view(struct item *);
void load(void);
struct item *head,*tail;
main(){
clrscr();
build();
view(head);
getch();
clrscr();
printf("\nfrom file");
load();
view(head);
getch();
}
void build(void)
{item *p,*pr;
pr=NULL;
do { p=(item *)malloc(sizeof(item));
clrscr();
printf("Name : ");
scanf("%s",&p->name);
printf("\nPrc : ");
scanf("%d",&p->prc);
printf("\nCol: ");
scanf("%d",&p->col);
p->prev=pr;
if(pr != NULL)
pr->next=p;
else
head=p;
pr=p;
printf("Esc");
}
while (getch()!=27);
tail=p;
tail->next=NULL;
}
void load(void)
{
item *p,*pr;
FILE *in;
while(p!=NULL)
{
p=p->next; //Clears memory
free(p);
}
in=fopen("data.txt","rb");
do{p=(item *)malloc(sizeof(item));
fread(p,sizeof(item),1,in);
p->prev=pr;
if(pr != NULL)
pr->next=p;
else
head=p;
pr=p;
printf("Esc");
}
while (!feof(in));
tail=p;
tail->next=NULL;
}
void view(item *p)
{
int i=1;
FILE *in;
clrscr();
in=fopen("data.txt","wb");
if( in != NULL )
{
while (p != NULL)
{
printf("\n %-2d %-15s\t%3d\t%3d",i,p->name, p->prc, p->col);
if(!fwrite(p, sizeof(item),1,in))
{
perror("fwrite");
getchar();
fclose(in);
return;
}
i++;
p = p->next;
}
fclose(in);
}
else
{
printf("Error: File cannot be created/opened\n");
printf("Press any key to continue...\n");
getchar();
return;
}
}