Here is my struct;
Code:
struct prs
{
char name[255];
int number;
struct prs *ptrnext;
};
struct prs *ptrfirst = NULL;
Here I enter a new member;
Code:
void newname()
{
struct prs *ptrthis;
char numstr[81];
ptrthis = malloc(sizeof(struct prs));
if(ptrthis == NULL)
{
printf("Allocation failed\n");
return;
}
ptrthis->ptrnext = ptrfirst
ptrfirst = ptrthis;
printf("\n\nEnter name: \n");
gets(ptrthis->name);
printf("\n\nEnter number: \n");
gets(numstr);
ptrthis->number = atoi(numstr);
}
Here I save my data to a file
Code:
void savetofile()
{
FILE *fp;
struct prs *ptrthis;
if(ptrfirst == NULL)
{
printf("Empty.\n");
return;
}
ptrthis = ptrfirst;
if((fp=fopen("c:\\database.txt", "wb")) == NULL)
{
printf("No such file.\n");
return;
}
else
{
fwrite(&ptrthis, sizeof(*ptrthis), 1, fp);
fclose(fp);
printf("Saved to disk.\n");
system("PAUSE");
}
}
Here I read from the file and print. And it's here that fread returns 0 :|
Code:
void readfromfile()
{
int nametemp;
int numbertemp = 0;
FILE *fp;
struct prs *ptrthis = malloc(sizeof(*ptrthis));
ptrthis = ptrfirst;
fp=fopen("c:\\database.txt", "ab");
while(fread(ptrthis, sizeof(*ptrthis), 1, fp) ==1)
{
printf("%s\n", ptrthis->name);
printf("%d\n", ptrthis->number);
ptrthis = ptrthis->ptrnext;
}
system("PAUSE");
}
Hopefully it's not to bad