I modified the program to make it simpler for demonstration.
The problem with this is that the program doesn't read properly what has been written. I think I am wrong in using my fread code.
Code:
#include <stdio.h>
#define INDEX 5
struct entry{
char name[20];
float owes;
}my_data[INDEX];
main()
{
char letra;
int x;
for(x=0;x<INDEX;x++)
{
my_data[x].owes=0;
}
do
{
clrscr();
printf("\nW-rite R-ead Q-uit");
letra=getch();
switch(toupper(letra))
{
case('W'):
writer();
break;
case('R'):
reader();
break;
case('Q'):
break;
}
}while((toupper(letra))!='Q');
}
writer()
{
int x;
float owe;
char st[20];
FILE *file_pointer;
printf("\nEnter no. ");
scanf("%d",&x);
printf("\nEnter name: ");
scanf("%s",&st);
strcpy(my_data[x-1].name,st);
printf("\nOwes? ");
scanf("%f",&owe);
my_data[x-1].owes=owe;
printf("\nWRITER");
if((file_pointer=fopen("writer.dat","a"))!=NULL)
fwrite(my_data,sizeof(struct entry),1,file_pointer);
else printf("Error writing writer.dat\n");
fclose(file_pointer);
getch();
}
reader()
{
FILE *file_pointer;
struct entry buffer[INDEX];
int rec_num,x;
if((file_pointer=fopen("writer.dat","r"))==NULL)
{
printf("Error reading writer.dat\n");
}
else
{
printf("\nTotal owes: ");
fread(&buffer,sizeof(struct entry),INDEX,file_pointer);
for(x=0;x<INDEX;x++)
{
printf("\nRecord %d %3.2f",x,buffer[x].owes);
}
fclose(file_pointer);
}
getch();
return(0);
}